SMimePart.php 2.7 KB

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