Created
July 12, 2022 21:41
-
-
Save ghostwriter/77bd330bfc8b897ee0e3d3e68faed4ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // AssertableValueObject.php | |
| final class AssertionsFailedException extends \RuntimeException | |
| { | |
| } | |
| interface AssertableInterface | |
| { | |
| /** | |
| * @param callable(self):bool $assertion | |
| */ | |
| public function assert(callable $assertion, string $reason = 'The assertion returned false'): void; | |
| } | |
| trait AssertableTrait | |
| { | |
| public function assert(callable $assertion, string $reason = ''): void | |
| { | |
| if(! ($assertion)($this)){ | |
| throw new AssertionsFailedException($reason); | |
| } | |
| } | |
| } | |
| final class ValueObject implements AssertableInterface | |
| { | |
| use AssertableTrait; | |
| private string $name; | |
| public function __construct(string $name) | |
| { | |
| $this->name = $name; | |
| $this->assert( | |
| static fn(self $my): bool => $my->name !== '', | |
| 'name is an empty string.' | |
| ); | |
| } | |
| } | |
| var_dump([ | |
| new ValueObject('p'), | |
| new ValueObject('') | |
| ]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment