Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace HelloWorldApp\ValueObject;
- abstract class VO
- {
- protected function __construct(
- protected mixed $value,
- )
- {
- }
- public function __toString(): string
- {
- return (string) $this->value;
- }
- }
- final class HumanName extends VO
- {
- public static function fromString(string $data)
- {
- if(strlen($data) < 3){
- throw new \DomainException("'$data' is not a human name");
- }
- return new self($data);
- }
- }
- class HumanNameDto
- {
- private HumanName $humanName;
- public function __construct(string|HumanName $humanName)
- {
- $this->humanName = match(true){
- is_string($humanName) => HumanName::fromString($humanName),
- is_object($humanName) && $humanName::class === HumanName::class => $humanName,
- };
- }
- public function getHumanName(): HumanName
- {
- return $this->humanName;
- }
- }
- $dto = new HumanNameDto('John');
- echo $dto->getHumanName() . PHP_EOL;
- echo $dto->getHumanName()::class . PHP_EOL;
- try{
- $name = HumanName::fromString('aa');
- } catch (\DomainException $e){
- echo PHP_EOL . 'Exception: ' . $e->getMessage() . PHP_EOL;
- }
Advertisement
Add Comment
Please, Sign In to add comment