SMimePart.php 2.3 KB

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