quenti77

ValueObject IPAddress

Aug 15th, 2025
134
0
12 hours
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.93 KB | None | 0 0
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace Domain\ValueObject;
  6.  
  7. use Domain\Enum\InternetProtocol;
  8. use InvalidArgumentException;
  9.  
  10. final readonly class IPAddress
  11. {
  12.     public function __construct(
  13.         // Si vraiment on veut du private il faut faire
  14.         // private private(set) InternetProtocol $protocol,
  15.         public InternetProtocol $protocol,
  16.         public string $value,
  17.     ) {
  18.         $this->assertValueWithProtocol();
  19.     }
  20.  
  21.     public function equals(IPAddress $other): bool
  22.     {
  23.         return $this->value === $other->value;
  24.     }
  25.  
  26.     public function notEquals(IPAddress $other): bool
  27.     {
  28.         return !$this->equals($other);
  29.     }
  30.  
  31.     private function assertValueWithProtocol(): void
  32.     {
  33.         if (!$this->protocol->supports($this->value)) {
  34.             throw new InvalidArgumentException("Invalid address '{$this->value}' for protocol '{$this->protocol->value}'");
  35.         }
  36.     }
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment