scratch – Blame information for rev
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
120 | office | 1 | <?php |
2 | |||
3 | /* |
||
4 | * This file is part of the Symfony package. |
||
5 | * |
||
6 | * (c) Fabien Potencier <fabien@symfony.com> |
||
7 | * |
||
8 | * For the full copyright and license information, please view the LICENSE |
||
9 | * file that was distributed with this source code. |
||
10 | */ |
||
11 | |||
12 | namespace Symfony\Component\Process; |
||
13 | |||
14 | use Symfony\Component\Process\Exception\RuntimeException; |
||
15 | |||
16 | /** |
||
17 | * Provides a way to continuously write to the input of a Process until the InputStream is closed. |
||
18 | * |
||
19 | * @author Nicolas Grekas <p@tchwork.com> |
||
20 | */ |
||
21 | class InputStream implements \IteratorAggregate |
||
22 | { |
||
23 | private $onEmpty = null; |
||
24 | private $input = array(); |
||
25 | private $open = true; |
||
26 | |||
27 | /** |
||
28 | * Sets a callback that is called when the write buffer becomes empty. |
||
29 | */ |
||
30 | public function onEmpty(callable $onEmpty = null) |
||
31 | { |
||
32 | $this->onEmpty = $onEmpty; |
||
33 | } |
||
34 | |||
35 | /** |
||
36 | * Appends an input to the write buffer. |
||
37 | * |
||
38 | * @param resource|scalar|\Traversable|null The input to append as stream resource, scalar or \Traversable |
||
39 | */ |
||
40 | public function write($input) |
||
41 | { |
||
42 | if (null === $input) { |
||
43 | return; |
||
44 | } |
||
45 | if ($this->isClosed()) { |
||
46 | throw new RuntimeException(sprintf('%s is closed', static::class)); |
||
47 | } |
||
48 | $this->input[] = ProcessUtils::validateInput(__METHOD__, $input); |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * Closes the write buffer. |
||
53 | */ |
||
54 | public function close() |
||
55 | { |
||
56 | $this->open = false; |
||
57 | } |
||
58 | |||
59 | /** |
||
60 | * Tells whether the write buffer is closed or not. |
||
61 | */ |
||
62 | public function isClosed() |
||
63 | { |
||
64 | return !$this->open; |
||
65 | } |
||
66 | |||
67 | public function getIterator() |
||
68 | { |
||
69 | $this->open = true; |
||
70 | |||
71 | while ($this->open || $this->input) { |
||
72 | if (!$this->input) { |
||
73 | yield ''; |
||
74 | continue; |
||
75 | } |
||
76 | $current = array_shift($this->input); |
||
77 | |||
78 | if ($current instanceof \Iterator) { |
||
79 | foreach ($current as $cur) { |
||
80 | yield $cur; |
||
81 | } |
||
82 | } else { |
||
83 | yield $current; |
||
84 | } |
||
85 | if (!$this->input && $this->open && null !== $onEmpty = $this->onEmpty) { |
||
86 | $this->write($onEmpty($this)); |
||
87 | } |
||
88 | } |
||
89 | } |
||
90 | } |