ProcessPool::wait()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 9
c 1
b 0
f 0
nc 5
nop 0
dl 0
loc 19
rs 9.6111
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Dandelion\Process;
6
7
use Closure;
8
9
class ProcessPool implements ProcessPoolInterface
10
{
11
    /**
12
     * @var \Symfony\Component\Process\Process[]
13
     */
14
    protected $runningProcesses;
15
16
    /**
17
     * @var \Symfony\Component\Process\Process[]
18
     */
19
    protected $processes;
20
21
    /**
22
     * @var \Closure[]
23
     */
24
    protected $callbacks;
25
26
    /**
27
     * @var \Dandelion\Process\ProcessFactory
28
     */
29
    protected $processFactory;
30
31
    /**
32
     * @param \Dandelion\Process\ProcessFactory $processFactory
33
     */
34
    public function __construct(
35
        ProcessFactory $processFactory
36
    ) {
37
        $this->processes = [];
38
        $this->callbacks = [];
39
        $this->runningProcesses = [];
40
        $this->processFactory = $processFactory;
41
    }
42
43
    /**
44
     * @param string[] $command
45
     * @param \Closure|null $callback
46
     *
47
     * @return \Dandelion\Process\ProcessPoolInterface
48
     */
49
    public function addProcess(array $command, ?Closure $callback = null): ProcessPoolInterface
50
    {
51
        $this->processes[] = $this->processFactory->create($command);
52
        $this->callbacks[] = $callback;
53
54
        return $this;
55
    }
56
57
    /**
58
     * @return \Dandelion\Process\ProcessPoolInterface
59
     */
60
    public function start(): ProcessPoolInterface
61
    {
62
        if (count($this->processes) === 0) {
63
            return $this;
64
        }
65
66
        foreach ($this->processes as $process) {
67
            $this->runningProcesses[] = $process;
68
            $process->start();
69
        }
70
71
        return $this->wait();
72
    }
73
74
    /**
75
     * @return \Dandelion\Process\ProcessPoolInterface
76
     */
77
    protected function wait(): ProcessPoolInterface
78
    {
79
        while (!empty($this->runningProcesses)) {
80
            foreach ($this->runningProcesses as $index => $runningProcess) {
81
                if ($runningProcess->isRunning()) {
82
                    continue;
83
                }
84
85
                if ($this->callbacks[$index] !== null) {
86
                    $this->callbacks[$index]($runningProcess);
87
                }
88
89
                unset($this->runningProcesses[$index]);
90
            }
91
92
            sleep(1);
93
        }
94
95
        return $this;
96
    }
97
}
98