Rfc2231Encoder.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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\CharacterStream;
  12. /**
  13. * @author Chris Corbyn
  14. */
  15. final class Rfc2231Encoder implements EncoderInterface
  16. {
  17. /**
  18. * Takes an unencoded string and produces a string encoded according to RFC 2231 from it.
  19. */
  20. public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string
  21. {
  22. $lines = [];
  23. $lineCount = 0;
  24. $lines[] = '';
  25. $currentLine = &$lines[$lineCount++];
  26. if (0 >= $maxLineLength) {
  27. $maxLineLength = 75;
  28. }
  29. $charStream = new CharacterStream($string, $charset);
  30. $thisLineLength = $maxLineLength - $firstLineOffset;
  31. while (null !== $char = $charStream->read(4)) {
  32. $encodedChar = rawurlencode($char);
  33. if (0 !== \strlen($currentLine) && \strlen($currentLine.$encodedChar) > $thisLineLength) {
  34. $lines[] = '';
  35. $currentLine = &$lines[$lineCount++];
  36. $thisLineLength = $maxLineLength;
  37. }
  38. $currentLine .= $encodedChar;
  39. }
  40. return implode("\r\n", $lines);
  41. }
  42. }