Base64ContentEncoder.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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\RuntimeException;
  12. /**
  13. * @author Fabien Potencier <fabien@symfony.com>
  14. */
  15. final class Base64ContentEncoder extends Base64Encoder implements ContentEncoderInterface
  16. {
  17. public function encodeByteStream($stream, int $maxLineLength = 0): iterable
  18. {
  19. if (!\is_resource($stream)) {
  20. throw new \TypeError(sprintf('Method "%s" takes a stream as a first argument.', __METHOD__));
  21. }
  22. $filter = stream_filter_append($stream, 'convert.base64-encode', \STREAM_FILTER_READ, [
  23. 'line-length' => 0 >= $maxLineLength || 76 < $maxLineLength ? 76 : $maxLineLength,
  24. 'line-break-chars' => "\r\n",
  25. ]);
  26. if (!\is_resource($filter)) {
  27. throw new RuntimeException('Unable to set the base64 content encoder to the filter.');
  28. }
  29. if (stream_get_meta_data($stream)['seekable'] ?? false) {
  30. rewind($stream);
  31. }
  32. while (!feof($stream)) {
  33. yield fread($stream, 8192);
  34. }
  35. stream_filter_remove($filter);
  36. }
  37. public function getName(): string
  38. {
  39. return 'base64';
  40. }
  41. }