Base64Encoder.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 Chris Corbyn
  13. */
  14. class Base64Encoder implements EncoderInterface
  15. {
  16. /**
  17. * Takes an unencoded string and produces a Base64 encoded string from it.
  18. *
  19. * Base64 encoded strings have a maximum line length of 76 characters.
  20. * If the first line needs to be shorter, indicate the difference with
  21. * $firstLineOffset.
  22. */
  23. public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string
  24. {
  25. if (0 >= $maxLineLength || 76 < $maxLineLength) {
  26. $maxLineLength = 76;
  27. }
  28. $encodedString = base64_encode($string);
  29. $firstLine = '';
  30. if (0 !== $firstLineOffset) {
  31. $firstLine = substr($encodedString, 0, $maxLineLength - $firstLineOffset)."\r\n";
  32. $encodedString = substr($encodedString, $maxLineLength - $firstLineOffset);
  33. }
  34. return $firstLine.trim(chunk_split($encodedString, $maxLineLength, "\r\n"));
  35. }
  36. }