AbstractMultipartPart.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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\Part;
  11. use Symfony\Component\Mime\Header\Headers;
  12. /**
  13. * @author Fabien Potencier <fabien@symfony.com>
  14. */
  15. abstract class AbstractMultipartPart extends AbstractPart
  16. {
  17. private $boundary;
  18. private $parts = [];
  19. public function __construct(AbstractPart ...$parts)
  20. {
  21. parent::__construct();
  22. foreach ($parts as $part) {
  23. $this->parts[] = $part;
  24. }
  25. }
  26. /**
  27. * @return AbstractPart[]
  28. */
  29. public function getParts(): array
  30. {
  31. return $this->parts;
  32. }
  33. public function getMediaType(): string
  34. {
  35. return 'multipart';
  36. }
  37. public function getPreparedHeaders(): Headers
  38. {
  39. $headers = parent::getPreparedHeaders();
  40. $headers->setHeaderParameter('Content-Type', 'boundary', $this->getBoundary());
  41. return $headers;
  42. }
  43. public function bodyToString(): string
  44. {
  45. $parts = $this->getParts();
  46. $string = '';
  47. foreach ($parts as $part) {
  48. $string .= '--'.$this->getBoundary()."\r\n".$part->toString()."\r\n";
  49. }
  50. $string .= '--'.$this->getBoundary()."--\r\n";
  51. return $string;
  52. }
  53. public function bodyToIterable(): iterable
  54. {
  55. $parts = $this->getParts();
  56. foreach ($parts as $part) {
  57. yield '--'.$this->getBoundary()."\r\n";
  58. yield from $part->toIterable();
  59. yield "\r\n";
  60. }
  61. yield '--'.$this->getBoundary()."--\r\n";
  62. }
  63. public function asDebugString(): string
  64. {
  65. $str = parent::asDebugString();
  66. foreach ($this->getParts() as $part) {
  67. $lines = explode("\n", $part->asDebugString());
  68. $str .= "\n └ ".array_shift($lines);
  69. foreach ($lines as $line) {
  70. $str .= "\n |".$line;
  71. }
  72. }
  73. return $str;
  74. }
  75. private function getBoundary(): string
  76. {
  77. if (null === $this->boundary) {
  78. $this->boundary = strtr(base64_encode(random_bytes(6)), '+/', '-_');
  79. }
  80. return $this->boundary;
  81. }
  82. }