RawMessage.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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;
  11. use Symfony\Component\Mime\Exception\LogicException;
  12. /**
  13. * @author Fabien Potencier <fabien@symfony.com>
  14. */
  15. class RawMessage
  16. {
  17. private bool $isGeneratorClosed;
  18. public function __construct(
  19. private iterable|string $message,
  20. ) {
  21. }
  22. public function toString(): string
  23. {
  24. if (\is_string($this->message)) {
  25. return $this->message;
  26. }
  27. $message = '';
  28. foreach ($this->message as $chunk) {
  29. $message .= $chunk;
  30. }
  31. return $this->message = $message;
  32. }
  33. public function toIterable(): iterable
  34. {
  35. if ($this->isGeneratorClosed ?? false) {
  36. throw new LogicException('Unable to send the email as its generator is already closed.');
  37. }
  38. if (\is_string($this->message)) {
  39. yield $this->message;
  40. return;
  41. }
  42. if ($this->message instanceof \Generator) {
  43. $message = '';
  44. foreach ($this->message as $chunk) {
  45. $message .= $chunk;
  46. yield $chunk;
  47. }
  48. $this->isGeneratorClosed = !$this->message->valid();
  49. $this->message = $message;
  50. return;
  51. }
  52. foreach ($this->message as $chunk) {
  53. yield $chunk;
  54. }
  55. }
  56. /**
  57. * @throws LogicException if the message is not valid
  58. */
  59. public function ensureValidity(): void
  60. {
  61. }
  62. public function __serialize(): array
  63. {
  64. return [$this->toString()];
  65. }
  66. public function __unserialize(array $data): void
  67. {
  68. [$this->message] = $data;
  69. }
  70. }