RawMessage.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. /**
  19. * @param iterable<string>|string|resource $message
  20. */
  21. public function __construct(
  22. private $message,
  23. ) {
  24. }
  25. public function __destruct()
  26. {
  27. if (\is_resource($this->message)) {
  28. fclose($this->message);
  29. }
  30. }
  31. public function toString(): string
  32. {
  33. if (\is_string($this->message)) {
  34. return $this->message;
  35. }
  36. if (\is_resource($this->message)) {
  37. return stream_get_contents($this->message, -1, 0);
  38. }
  39. $message = '';
  40. foreach ($this->message as $chunk) {
  41. $message .= $chunk;
  42. }
  43. return $this->message = $message;
  44. }
  45. public function toIterable(): iterable
  46. {
  47. if ($this->isGeneratorClosed ?? false) {
  48. throw new LogicException('Unable to send the email as its generator is already closed.');
  49. }
  50. if (\is_string($this->message)) {
  51. yield $this->message;
  52. return;
  53. }
  54. if (\is_resource($this->message)) {
  55. rewind($this->message);
  56. while ($line = fgets($this->message)) {
  57. yield $line;
  58. }
  59. return;
  60. }
  61. if ($this->message instanceof \Generator) {
  62. $message = fopen('php://temp', 'w+');
  63. foreach ($this->message as $chunk) {
  64. fwrite($message, $chunk);
  65. yield $chunk;
  66. }
  67. $this->isGeneratorClosed = !$this->message->valid();
  68. $this->message = $message;
  69. return;
  70. }
  71. foreach ($this->message as $chunk) {
  72. yield $chunk;
  73. }
  74. }
  75. /**
  76. * @throws LogicException if the message is not valid
  77. */
  78. public function ensureValidity(): void
  79. {
  80. }
  81. public function __serialize(): array
  82. {
  83. return [$this->toString()];
  84. }
  85. public function __unserialize(array $data): void
  86. {
  87. [$this->message] = $data;
  88. }
  89. }