You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.3 KiB

3 years ago
  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. }