RawMessage.php 2.6 KB

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