InputStream.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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\Process;
  11. use Symfony\Component\Process\Exception\RuntimeException;
  12. /**
  13. * Provides a way to continuously write to the input of a Process until the InputStream is closed.
  14. *
  15. * @author Nicolas Grekas <p@tchwork.com>
  16. *
  17. * @implements \IteratorAggregate<int, string>
  18. */
  19. class InputStream implements \IteratorAggregate
  20. {
  21. /** @var callable|null */
  22. private $onEmpty;
  23. private $input = [];
  24. private $open = true;
  25. /**
  26. * Sets a callback that is called when the write buffer becomes empty.
  27. *
  28. * @return void
  29. */
  30. public function onEmpty(?callable $onEmpty = null)
  31. {
  32. $this->onEmpty = $onEmpty;
  33. }
  34. /**
  35. * Appends an input to the write buffer.
  36. *
  37. * @param resource|string|int|float|bool|\Traversable|null $input The input to append as scalar,
  38. * stream resource or \Traversable
  39. *
  40. * @return void
  41. */
  42. public function write(mixed $input)
  43. {
  44. if (null === $input) {
  45. return;
  46. }
  47. if ($this->isClosed()) {
  48. throw new RuntimeException(sprintf('"%s" is closed.', static::class));
  49. }
  50. $this->input[] = ProcessUtils::validateInput(__METHOD__, $input);
  51. }
  52. /**
  53. * Closes the write buffer.
  54. *
  55. * @return void
  56. */
  57. public function close()
  58. {
  59. $this->open = false;
  60. }
  61. /**
  62. * Tells whether the write buffer is closed or not.
  63. *
  64. * @return bool
  65. */
  66. public function isClosed()
  67. {
  68. return !$this->open;
  69. }
  70. public function getIterator(): \Traversable
  71. {
  72. $this->open = true;
  73. while ($this->open || $this->input) {
  74. if (!$this->input) {
  75. yield '';
  76. continue;
  77. }
  78. $current = array_shift($this->input);
  79. if ($current instanceof \Iterator) {
  80. yield from $current;
  81. } else {
  82. yield $current;
  83. }
  84. if (!$this->input && $this->open && null !== $onEmpty = $this->onEmpty) {
  85. $this->write($onEmpty($this));
  86. }
  87. }
  88. }
  89. }