Guest User

Untitled

a guest
Mar 27th, 2024
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.13 KB | None | 0 0
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace HelloWorldApp\ValueObject;
  6.  
  7. abstract class VO
  8. {
  9.     protected function __construct(
  10.         protected mixed $value,    
  11.     )
  12.     {
  13.     }
  14.    
  15.     public function __toString(): string
  16.     {
  17.         return (string) $this->value;  
  18.     }
  19. }
  20.  
  21. final class HumanName extends VO
  22. {
  23.     public static function fromString(string $data)
  24.     {
  25.         if(strlen($data) < 3){
  26.             throw new \DomainException("'$data' is not a human name");
  27.         }
  28.        
  29.         return new self($data);
  30.     }
  31. }
  32.  
  33. class HumanNameDto
  34. {
  35.     private HumanName $humanName;
  36.    
  37.     public function __construct(string|HumanName $humanName)
  38.     {
  39.         $this->humanName = match(true){
  40.             is_string($humanName) => HumanName::fromString($humanName),
  41.             is_object($humanName) && $humanName::class === HumanName::class => $humanName,
  42.         };
  43.     }
  44.    
  45.     public function getHumanName(): HumanName
  46.     {
  47.         return $this->humanName;
  48.     }
  49. }
  50.  
  51.  
  52. $dto = new HumanNameDto('John');
  53. echo $dto->getHumanName() . PHP_EOL;
  54. echo $dto->getHumanName()::class . PHP_EOL;
  55.  
  56.  
  57. try{
  58.     $name = HumanName::fromString('aa');   
  59. } catch (\DomainException $e){
  60.     echo PHP_EOL . 'Exception: ' . $e->getMessage() . PHP_EOL;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment