Address.php 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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 (preg_match('/[\x00-\x1F\x7F]/', $this->address)) {
  44. throw new InvalidArgumentException('Email address contains control characters.');
  45. }
  46. if (!self::$validator->isValid($this->address, class_exists(MessageIDValidation::class) ? new MessageIDValidation() : new RFCValidation())) {
  47. throw new RfcComplianceException(\sprintf('Email "%s" does not comply with addr-spec of RFC 2822.', $address));
  48. }
  49. }
  50. public function getAddress(): string
  51. {
  52. return $this->address;
  53. }
  54. public function getName(): string
  55. {
  56. return $this->name;
  57. }
  58. public function getEncodedAddress(): string
  59. {
  60. self::$encoder ??= new IdnAddressEncoder();
  61. return self::$encoder->encodeString($this->address);
  62. }
  63. public function toString(): string
  64. {
  65. return ($n = $this->getEncodedName()) ? $n.' <'.$this->getEncodedAddress().'>' : $this->getEncodedAddress();
  66. }
  67. public function getEncodedName(): string
  68. {
  69. if ('' === $this->getName()) {
  70. return '';
  71. }
  72. return \sprintf('"%s"', preg_replace('/"/u', '\"', $this->getName()));
  73. }
  74. public static function create(self|string $address): self
  75. {
  76. if ($address instanceof self) {
  77. return $address;
  78. }
  79. if (!str_contains($address, '<')) {
  80. return new self($address);
  81. }
  82. if (!preg_match(self::FROM_STRING_PATTERN, $address, $matches)) {
  83. throw new InvalidArgumentException(\sprintf('Could not parse "%s" to a "%s" instance.', $address, self::class));
  84. }
  85. return new self($matches['addrSpec'], trim($matches['displayName'], ' \'"'));
  86. }
  87. /**
  88. * @param array<Address|string> $addresses
  89. *
  90. * @return Address[]
  91. */
  92. public static function createArray(array $addresses): array
  93. {
  94. $addrs = [];
  95. foreach ($addresses as $address) {
  96. $addrs[] = self::create($address);
  97. }
  98. return $addrs;
  99. }
  100. /**
  101. * Returns true if this address' localpart contains at least one
  102. * non-ASCII character, and false if it is only ASCII (or empty).
  103. *
  104. * This is a helper for Envelope, which has to decide whether to
  105. * the SMTPUTF8 extensions (RFC 6530 and following) for any given
  106. * message.
  107. *
  108. * The SMTPUTF8 extension is strictly required if any address
  109. * contains a non-ASCII character in its localpart. If non-ASCII
  110. * is only used in domains (e.g. horst@freiherr-von-mühlhausen.de)
  111. * then it is possible to send the message using IDN encoding
  112. * instead of SMTPUTF8. The most common software will display the
  113. * message as intended.
  114. */
  115. public function hasUnicodeLocalpart(): bool
  116. {
  117. return (bool) preg_match('/[\x80-\xFF].*@/', $this->address);
  118. }
  119. }