SMimePart.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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 Sebastiaan Stok <s.stok@rollerscapes.net>
  14. */
  15. class SMimePart extends AbstractPart
  16. {
  17. /** @internal */
  18. protected Headers $_headers;
  19. private iterable|string $body;
  20. private string $type;
  21. private string $subtype;
  22. private array $parameters;
  23. public function __construct(iterable|string $body, string $type, string $subtype, array $parameters)
  24. {
  25. parent::__construct();
  26. $this->body = $body;
  27. $this->type = $type;
  28. $this->subtype = $subtype;
  29. $this->parameters = $parameters;
  30. }
  31. public function getMediaType(): string
  32. {
  33. return $this->type;
  34. }
  35. public function getMediaSubtype(): string
  36. {
  37. return $this->subtype;
  38. }
  39. public function bodyToString(): string
  40. {
  41. if (\is_string($this->body)) {
  42. return $this->body;
  43. }
  44. $body = '';
  45. foreach ($this->body as $chunk) {
  46. $body .= $chunk;
  47. }
  48. $this->body = $body;
  49. return $body;
  50. }
  51. public function bodyToIterable(): iterable
  52. {
  53. if (\is_string($this->body)) {
  54. yield $this->body;
  55. return;
  56. }
  57. $body = '';
  58. foreach ($this->body as $chunk) {
  59. $body .= $chunk;
  60. yield $chunk;
  61. }
  62. $this->body = $body;
  63. }
  64. public function getPreparedHeaders(): Headers
  65. {
  66. $headers = clone parent::getHeaders();
  67. $headers->setHeaderBody('Parameterized', 'Content-Type', $this->getMediaType().'/'.$this->getMediaSubtype());
  68. foreach ($this->parameters as $name => $value) {
  69. $headers->setHeaderParameter('Content-Type', $name, $value);
  70. }
  71. return $headers;
  72. }
  73. public function __sleep(): array
  74. {
  75. // convert iterables to strings for serialization
  76. if (is_iterable($this->body)) {
  77. $this->body = $this->bodyToString();
  78. }
  79. $this->_headers = $this->getHeaders();
  80. return ['_headers', 'body', 'type', 'subtype', 'parameters'];
  81. }
  82. public function __wakeup(): void
  83. {
  84. $r = new \ReflectionProperty(AbstractPart::class, 'headers');
  85. $r->setValue($this, $this->_headers);
  86. unset($this->_headers);
  87. }
  88. }