final class Address
{
private $street;
private $unit;
private $room;
public function __construct(string $street, int $unit, ?int $room = null)
{
$this->street = $street;
$this->unit = $this->handleNumberArgument($unit);
$this->room = $room ? $this->handleNumberArgument($room) : null;
}
public function assignRoom(int $room): self
{
if (null !== $this->room) {
throw new LogicException('The room is already assigned to this address');
}
return new self($this->street, $this->unit, $room);
}
public function __toString(): string
{
return implode(',', [$this->street, $this->unit, $this->room ?? '']);
}
private function handleNumberArgument($value): int
{
if ($value <= 0) {
throw new InvalidArgumentException('Number must be more than \'0\'');
}
return $value;
}
}
final class UserRegisterRequest
{
public const PASSWORD_MIN_LENGTH = 6;
public $username;
public $password;
private function __construct(string $username, string $password)
{
$this->username = $username;
$this->assertPasswordLength($password);
$this->password = $password;
}
public static function create(string $username, string $password): self
{
return new self($username, $password);
}
private function assertPasswordLength(string $password)
{
if (self::PASSWORD_MIN_LENGTH >= strlen($password)) {
throw new InvalidArgumentException('Password must be more than 6 characters.');
}
}
}