InputStream.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 null|callable */
  20. private $onEmpty = null;
  21. private $input = array();
  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 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. public function getIterator()
  61. {
  62. $this->open = true;
  63. while ($this->open || $this->input) {
  64. if (!$this->input) {
  65. yield '';
  66. continue;
  67. }
  68. $current = array_shift($this->input);
  69. if ($current instanceof \Iterator) {
  70. foreach ($current as $cur) {
  71. yield $cur;
  72. }
  73. } else {
  74. yield $current;
  75. }
  76. if (!$this->input && $this->open && null !== $onEmpty = $this->onEmpty) {
  77. $this->write($onEmpty($this));
  78. }
  79. }
  80. }
  81. }