IdnAddressEncoder.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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\Encoder;
  11. use Symfony\Component\Mime\Exception\AddressEncoderException;
  12. /**
  13. * An IDN email address encoder.
  14. *
  15. * Encodes the domain part of an address using IDN. This is compatible will all
  16. * SMTP servers.
  17. *
  18. * This encoder does not support email addresses with non-ASCII characters in
  19. * local-part (the substring before @).
  20. *
  21. * @author Christian Schmidt
  22. */
  23. final class IdnAddressEncoder implements AddressEncoderInterface
  24. {
  25. /**
  26. * Encodes the domain part of an address using IDN.
  27. *
  28. * @throws AddressEncoderException If local-part contains non-ASCII characters
  29. */
  30. public function encodeString(string $address): string
  31. {
  32. $i = strrpos($address, '@');
  33. if (false !== $i) {
  34. $local = substr($address, 0, $i);
  35. $domain = substr($address, $i + 1);
  36. if (preg_match('/[^\x00-\x7F]/', $local)) {
  37. throw new AddressEncoderException(sprintf('Non-ASCII characters not supported in local-part os "%s".', $address));
  38. }
  39. if (preg_match('/[^\x00-\x7F]/', $domain)) {
  40. $address = sprintf('%s@%s', $local, idn_to_ascii($domain, \IDNA_DEFAULT | \IDNA_USE_STD3_RULES | \IDNA_CHECK_BIDI | \IDNA_CHECK_CONTEXTJ | \IDNA_NONTRANSITIONAL_TO_ASCII, \INTL_IDNA_VARIANT_UTS46));
  41. }
  42. }
  43. return $address;
  44. }
  45. }