* SPDX-License-Identifier: AGPL-3.0-or-later */ namespace KTXF\Mail\Object; /** * Address Implementation * * @since 2025.05.01 */ class Address implements AddressInterface { /** * @param string $address Email address * @param string|null $name Display name */ public function __construct( private string $address = '', private ?string $name = null, ) {} /** * @inheritDoc */ public function jsonSerialize(): array { return array_filter([ self::JSON_PROPERTY_ADDRESS => $this->address, self::JSON_PROPERTY_LABEL => $this->name, ], fn($v) => $v !== null && $v !== ''); } /** * Creates an Address from a formatted string * * @since 2025.05.01 * * @param string $value Formatted as "Name
" or just "address" * * @return self */ public static function fromString(string $value): self { $value = trim($value); // Match "Name " format if (preg_match('/^(.+?)\s*<([^>]+)>$/', $value, $matches)) { return new self(trim($matches[2]), trim($matches[1], ' "\'')); } // Match "" format if (preg_match('/^<([^>]+)>$/', $value, $matches)) { return new self(trim($matches[1])); } // Assume plain address return new self($value); } /** * Creates an Address from an array * * @since 2025.05.01 * * @param array $data Array with 'address' and optional 'name' keys * * @return self */ public static function fromArray(array $data): self { return new self( $data[self::JSON_PROPERTY_ADDRESS] ?? $data['address'] ?? '', $data[self::JSON_PROPERTY_LABEL] ?? $data['name'] ?? null, ); } /** * @inheritDoc */ public function getAddress(): string { return $this->address; } /** * @inheritDoc */ public function setAddress(string $address): static { $this->address = $address; return $this; } /** * @inheritDoc */ public function getLabel(): ?string { return $this->name; } /** * @inheritDoc */ public function setLabel(?string $label): static { $this->name = $label; return $this; } /** * @inheritDoc */ public function toString(): string { if ($this->name !== null && $this->name !== '') { return sprintf('"%s" <%s>', $this->name, $this->address); } return $this->address; } /** * String representation */ public function __toString(): string { return $this->toString(); } }