1 | <?php |
||
19 | class ProcessQueue implements \Countable |
||
20 | { |
||
21 | const SLEEP_MICRO_SECONDS = 1000; |
||
22 | const PROMISE_KEY = 'promise'; |
||
23 | |||
24 | /** |
||
25 | * @var int |
||
26 | */ |
||
27 | private $limit; |
||
28 | |||
29 | /** |
||
30 | * @var Collection |
||
31 | */ |
||
32 | private $queue; |
||
33 | |||
34 | /** |
||
35 | * ProcessQueue constructor |
||
36 | * |
||
37 | * @param int $limit |
||
38 | */ |
||
39 | 18 | public function __construct($limit = null) |
|
48 | |||
49 | /** |
||
50 | * Add new process to the queue |
||
51 | * |
||
52 | * @param Process $process |
||
53 | * @return $this |
||
54 | */ |
||
55 | 13 | public function add(Process $process) |
|
61 | |||
62 | /** |
||
63 | * Return pending processes |
||
64 | * |
||
65 | * @return Collection |
||
66 | */ |
||
67 | 6 | public function getPending() |
|
73 | |||
74 | /** |
||
75 | * Return running processes |
||
76 | * |
||
77 | * @return Collection |
||
78 | */ |
||
79 | 6 | public function getRunning() |
|
85 | |||
86 | /** |
||
87 | * Return completed processes |
||
88 | * |
||
89 | * @return Collection |
||
90 | */ |
||
91 | 6 | public function getCompleted() |
|
97 | |||
98 | /** |
||
99 | * Clear and resolve completed processes from the queue |
||
100 | * |
||
101 | * @return void |
||
102 | */ |
||
103 | private function clearCompleted() |
||
110 | |||
111 | /** |
||
112 | * Halt execution and wait for target process to finish |
||
113 | * |
||
114 | * @param Process $process |
||
115 | */ |
||
116 | 7 | public function resolve(Process $process) |
|
127 | |||
128 | /** |
||
129 | * Run the queue |
||
130 | * |
||
131 | * @return \Generator |
||
132 | */ |
||
133 | 5 | public function __invoke() |
|
134 | { |
||
135 | 5 | while (!$this->queue->isEmpty()) { |
|
136 | 5 | usleep(self::SLEEP_MICRO_SECONDS); |
|
137 | |||
138 | 5 | $pending = $this->getPending(); |
|
139 | |||
140 | 5 | if ($pending->count() && $this->getRunning()->count() < $this->limit) { |
|
141 | 5 | yield $pending->shift(); |
|
142 | 5 | } else { |
|
143 | 5 | yield new NullProcess(); |
|
144 | } |
||
145 | |||
146 | 5 | $this->clearCompleted(); |
|
147 | 5 | } |
|
148 | 5 | } |
|
149 | |||
150 | /** |
||
151 | * Return queue count |
||
152 | * |
||
153 | * @return int |
||
154 | */ |
||
155 | 6 | public function count() |
|
159 | } |
||
160 |