1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Mime;
13
14use Egulias\EmailValidator\EmailValidator;
15use Egulias\EmailValidator\Validation\RFCValidation;
16use Symfony\Component\Mime\Encoder\IdnAddressEncoder;
17use Symfony\Component\Mime\Exception\InvalidArgumentException;
18use Symfony\Component\Mime\Exception\LogicException;
19use Symfony\Component\Mime\Exception\RfcComplianceException;
20
21/**
22 * @author Fabien Potencier <fabien@symfony.com>
23 */
24final class Address
25{
26 /**
27 * A regex that matches a structure like 'Name <email@address.com>'.
28 * It matches anything between the first < and last > as email address.
29 * This allows to use a single string to construct an Address, which can be convenient to use in
30 * config, and allows to have more readable config.
31 * This does not try to cover all edge cases for address.
32 */
33 private const FROM_STRING_PATTERN = '~(?<displayName>[^<]*)<(?<addrSpec>.*)>[^>]*~';
34
35 private static $validator;
36 private static $encoder;
37
38 private $address;
39 private $name;
40
41 public function __construct(string $address, string $name = '')
42 {
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));
45 }
46
47 if (null === self::$validator) {
48 self::$validator = new EmailValidator();
49 }
50
51 $this->address = trim($address);
52 $this->name = trim(str_replace(["\n", "\r"], '', $name));
53
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));
56 }
57 }
58
59 public function getAddress(): string
60 {
61 return $this->address;
62 }
63
64 public function getName(): string
65 {
66 return $this->name;
67 }
68
69 public function getEncodedAddress(): string
70 {
71 if (null === self::$encoder) {
72 self::$encoder = new IdnAddressEncoder();
73 }
74
75 return self::$encoder->encodeString($this->address);
76 }
77
78 public function toString(): string
79 {
80 return ($n = $this->getName()) ? $n.' <'.$this->getEncodedAddress().'>' : $this->getEncodedAddress();
81 }
82
83 /**
84 * @param Address|string $address
85 */
86 public static function create($address): self
87 {
88 if ($address instanceof self) {
89 return $address;
90 }
91 if (\is_string($address)) {
92 return self::fromString($address);
93 }
94
95 throw new InvalidArgumentException(sprintf('An address can be an instance of Address or a string ("%s") given).', get_debug_type($address)));
96 }
97
98 /**
99 * @param (Address|string)[] $addresses
100 *
101 * @return Address[]
102 */
103 public static function createArray(array $addresses): array
104 {
105 $addrs = [];
106 foreach ($addresses as $address) {
107 $addrs[] = self::create($address);
108 }
109
110 return $addrs;
111 }
112
113 public static function fromString(string $string): self
114 {
115 if (false === strpos($string, '<')) {
116 return new self($string, '');
117 }
118
119 if (!preg_match(self::FROM_STRING_PATTERN, $string, $matches)) {
120 throw new InvalidArgumentException(sprintf('Could not parse "%s" to a "%s" instance.', $string, static::class));
121 }
122
123 return new self($matches['addrSpec'], trim($matches['displayName'], ' \'"'));
124 }
125}
126