Skip to content

Instantly share code, notes, and snippets.

@ghostwriter
Created July 12, 2022 21:41
Show Gist options
  • Select an option

  • Save ghostwriter/77bd330bfc8b897ee0e3d3e68faed4ec to your computer and use it in GitHub Desktop.

Select an option

Save ghostwriter/77bd330bfc8b897ee0e3d3e68faed4ec to your computer and use it in GitHub Desktop.
<?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