You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.3 KiB

3 years ago
  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. public function getIterator()
  64. {
  65. $this->open = true;
  66. while ($this->open || $this->input) {
  67. if (!$this->input) {
  68. yield '';
  69. continue;
  70. }
  71. $current = array_shift($this->input);
  72. if ($current instanceof \Iterator) {
  73. yield from $current;
  74. } else {
  75. yield $current;
  76. }
  77. if (!$this->input && $this->open && null !== $onEmpty = $this->onEmpty) {
  78. $this->write($onEmpty($this));
  79. }
  80. }
  81. }
  82. }