QpContentEncoder.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. /**
  12. * @author Lars Strojny
  13. */
  14. final class QpContentEncoder implements ContentEncoderInterface
  15. {
  16. public function encodeByteStream($stream, int $maxLineLength = 0): iterable
  17. {
  18. if (!\is_resource($stream)) {
  19. throw new \TypeError(sprintf('Method "%s" takes a stream as a first argument.', __METHOD__));
  20. }
  21. // we don't use PHP stream filters here as the content should be small enough
  22. yield $this->encodeString(stream_get_contents($stream), 'utf-8', 0, $maxLineLength);
  23. }
  24. public function getName(): string
  25. {
  26. return 'quoted-printable';
  27. }
  28. public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string
  29. {
  30. return $this->standardize(quoted_printable_encode($string));
  31. }
  32. /**
  33. * Make sure CRLF is correct and HT/SPACE are in valid places.
  34. */
  35. private function standardize(string $string): string
  36. {
  37. // transform CR or LF to CRLF
  38. $string = preg_replace('~=0D(?!=0A)|(?<!=0D)=0A~', '=0D=0A', $string);
  39. // transform =0D=0A to CRLF
  40. $string = str_replace(["\t=0D=0A", ' =0D=0A', '=0D=0A'], ["=09\r\n", "=20\r\n", "\r\n"], $string);
  41. switch (\ord(substr($string, -1))) {
  42. case 0x09:
  43. $string = substr_replace($string, '=09', -1);
  44. break;
  45. case 0x20:
  46. $string = substr_replace($string, '=20', -1);
  47. break;
  48. }
  49. return $string;
  50. }
  51. }