Files
server/shared/lib/Mail/Object/Address.php
Sebastian 869f2e4fb4
JS Unit Tests / test (pull_request) Successful in 23s
Build Test / build (pull_request) Successful in 26s
PHP Unit Tests / test (pull_request) Successful in 52s
refactor: message object properties
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-06-16 13:12:30 -04:00

135 lines
2.9 KiB
PHP

<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* 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,
) {}
/**
* Creates an Address from a formatted string
*
* @since 2025.05.01
*
* @param string $value Formatted as "Name <address>" or just "address"
*
* @return self
*/
public static function fromString(string $value): self {
$value = trim($value);
// Match "Name <address>" format
if (preg_match('/^(.+?)\s*<([^>]+)>$/', $value, $matches)) {
return new self(trim($matches[2]), trim($matches[1], ' "\''));
}
// Match "<address>" 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<address: string, label: string|null> $data
*
* @return self
*/
public static function fromArray(array $data): self {
return new self(
$data[self::PROPERTY_ADDRESS] ?? $data['address'] ?? '',
$data[self::PROPERTY_LABEL] ?? $data['label'] ?? null,
);
}
/**
* @inheritDoc
*/
public function jsonSerialize(): array {
return array_filter([
self::PROPERTY_ADDRESS => $this->address,
self::PROPERTY_LABEL => $this->name,
], fn($v) => $v !== null && $v !== '');
}
/**
* @inheritDoc
*/
public function toArray(): array {
return $this->jsonSerialize();
}
/**
* @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();
}
}