14 use Egulias\EmailValidator\EmailValidator;
15 use Egulias\EmailValidator\Validation\RFCValidation;
33 private const FROM_STRING_PATTERN =
'~(?<displayName>[^<]*)<(?<addrSpec>.*)>[^>]*~';
35 private static $validator;
36 private static $encoder;
41 public function __construct(
string $address,
string $name =
'')
43 if (!class_exists(EmailValidator::class)) {
44 throw new LogicException(sprintf(
'The "%s" class cannot be used as it needs "%s"; try running "composer require egulias/email-validator".', __CLASS__, EmailValidator::class));
47 if (
null === self::$validator) {
48 self::$validator =
new EmailValidator();
51 $this->address = trim($address);
52 $this->name = trim(str_replace([
"\n",
"\r"],
'', $name));
54 if (!self::$validator->isValid($this->address,
new RFCValidation())) {
55 throw new RfcComplianceException(sprintf(
'Email "%s" does not comply with addr-spec of RFC 2822.', $address));
61 return $this->address;
71 if (
null === self::$encoder) {
75 return self::$encoder->encodeString($this->address);
86 public static function create($address): self
88 if ($address instanceof
self) {
91 if (\is_string($address)) {
92 return new self($address);
95 throw new InvalidArgumentException(sprintf(
'An address can be an instance of Address or a string ("%s") given).', \is_object($address) ? \get_class($address) : \gettype($address)));
106 foreach ($addresses as $address) {
115 if (
false === strpos($string,
'<')) {
116 return new self($string,
'');
119 if (!preg_match(self::FROM_STRING_PATTERN, $string, $matches)) {
123 return new self($matches[
'addrSpec'], trim($matches[
'displayName'],
' \'"'));