InputStream.php 2.2 KB

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