Address.php 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mime;
  11. use Egulias\EmailValidator\EmailValidator;
  12. use Egulias\EmailValidator\Validation\MessageIDValidation;
  13. use Egulias\EmailValidator\Validation\RFCValidation;
  14. use Symfony\Component\Mime\Encoder\IdnAddressEncoder;
  15. use Symfony\Component\Mime\Exception\InvalidArgumentException;
  16. use Symfony\Component\Mime\Exception\LogicException;
  17. use Symfony\Component\Mime\Exception\RfcComplianceException;
  18. /**
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. final class Address
  22. {
  23. /**
  24. * A regex that matches a structure like 'Name <email@address.com>'.
  25. * It matches anything between the first < and last > as email address.
  26. * This allows to use a single string to construct an Address, which can be convenient to use in
  27. * config, and allows to have more readable config.
  28. * This does not try to cover all edge cases for address.
  29. */
  30. private const FROM_STRING_PATTERN = '~(?<displayName>[^<]*)<(?<addrSpec>.*)>[^>]*~';
  31. private static EmailValidator $validator;
  32. private static IdnAddressEncoder $encoder;
  33. private string $address;
  34. private string $name;
  35. public function __construct(string $address, string $name = '')
  36. {
  37. if (!class_exists(EmailValidator::class)) {
  38. throw new LogicException(\sprintf('The "%s" class cannot be used as it needs "%s". Try running "composer require egulias/email-validator".', __CLASS__, EmailValidator::class));
  39. }
  40. self::$validator ??= new EmailValidator();
  41. $this->address = trim($address);
  42. $this->name = trim(str_replace(["\n", "\r"], '', $name));
  43. if (!self::$validator->isValid($this->address, class_exists(MessageIDValidation::class) ? new MessageIDValidation() : new RFCValidation())) {
  44. throw new RfcComplianceException(\sprintf('Email "%s" does not comply with addr-spec of RFC 2822.', $address));
  45. }
  46. }
  47. public function getAddress(): string
  48. {
  49. return $this->address;
  50. }
  51. public function getName(): string
  52. {
  53. return $this->name;
  54. }
  55. public function getEncodedAddress(): string
  56. {
  57. self::$encoder ??= new IdnAddressEncoder();
  58. return self::$encoder->encodeString($this->address);
  59. }
  60. public function toString(): string
  61. {
  62. return ($n = $this->getEncodedName()) ? $n.' <'.$this->getEncodedAddress().'>' : $this->getEncodedAddress();
  63. }
  64. public function getEncodedName(): string
  65. {
  66. if ('' === $this->getName()) {
  67. return '';
  68. }
  69. return \sprintf('"%s"', preg_replace('/"/u', '\"', $this->getName()));
  70. }
  71. public static function create(self|string $address): self
  72. {
  73. if ($address instanceof self) {
  74. return $address;
  75. }
  76. if (!str_contains($address, '<')) {
  77. return new self($address);
  78. }
  79. if (!preg_match(self::FROM_STRING_PATTERN, $address, $matches)) {
  80. throw new InvalidArgumentException(\sprintf('Could not parse "%s" to a "%s" instance.', $address, self::class));
  81. }
  82. return new self($matches['addrSpec'], trim($matches['displayName'], ' \'"'));
  83. }
  84. /**
  85. * @param array<Address|string> $addresses
  86. *
  87. * @return Address[]
  88. */
  89. public static function createArray(array $addresses): array
  90. {
  91. $addrs = [];
  92. foreach ($addresses as $address) {
  93. $addrs[] = self::create($address);
  94. }
  95. return $addrs;
  96. }
  97. /**
  98. * Returns true if this address' localpart contains at least one
  99. * non-ASCII character, and false if it is only ASCII (or empty).
  100. *
  101. * This is a helper for Envelope, which has to decide whether to
  102. * the SMTPUTF8 extensions (RFC 6530 and following) for any given
  103. * message.
  104. *
  105. * The SMTPUTF8 extension is strictly required if any address
  106. * contains a non-ASCII character in its localpart. If non-ASCII
  107. * is only used in domains (e.g. horst@freiherr-von-mühlhausen.de)
  108. * then it is possible to send the message using IDN encoding
  109. * instead of SMTPUTF8. The most common software will display the
  110. * message as intended.
  111. */
  112. public function hasUnicodeLocalpart(): bool
  113. {
  114. return (bool) preg_match('/[\x80-\xFF].*@/', $this->address);
  115. }
  116. }