Aucune description

InputStream.php 2.3KB

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