Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(expectations): add toMatchConstraint #190

Merged
merged 2 commits into from
Sep 21, 2020
Merged

feat(expectations): add toMatchConstraint #190

merged 2 commits into from
Sep 21, 2020

Conversation

owenvoke
Copy link
Member

@owenvoke owenvoke commented Sep 17, 2020

Q A
Bug fix? no
New feature? yes
Fixed tickets #...

This allows the use of Constraint classes for more complex validation.

// From basic constraints
expect(true)->toMatchConstraint(new IsTrue());

// To more complex constraints
expect(true)->toMatchConstraint(
    $this->logicalAnd(
         $this->logicalNot(new IsFalse()),
         new IsType(IsType::TYPE_BOOL)
    )
);

// To custom constraints
expect('https://google.com')->toMatchConstraint(new IsValidUrlConstraint());

class IsValidUrlConstraint extends PHPUnit\Framework\Constraint
{
    public function toString()
    {
        return 'is a valid url';
    }

    protected function matches($other): bool
    {
        if (! is_string($other)) {
            return false;
        }

        return preg_match(
            Symfony\Component\Validator\Constraints\UrlValidator::PATTERN,
            $other
        ) > 0;
    }
}

Custom constraints should extend PHPUnit\Framework\Constraint, and provide a matches() and toString() method, and optionally override the evaluate() method.

Copy link
Member

@nunomaduro nunomaduro left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can add this.

@owenvoke
Copy link
Member Author

owenvoke commented Sep 17, 2020

I'll add the docs for it tomorrow. 👍

pestphp/website#89

@owenvoke owenvoke merged commit 2811664 into pestphp:master Sep 21, 2020
@owenvoke owenvoke deleted the feature/assert-constraint branch September 21, 2020 19:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants