ParallelProcessor::wait()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
dl 0
loc 7
rs 10
c 1
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
4
namespace Tohidplus\Paravel\Process;
5
6
use Closure;
7
use Tohidplus\Paravel\Facades\Serializer;
8
use Tohidplus\Paravel\Response\ResponseList;
9
10
class ParallelProcessor
11
{
12
    /**
13
     * @var Process[] $processes
14
     */
15
    protected array $processes = [];
16
17
    /**
18
     * @var array
19
     */
20
    private array $config;
21
22
    /**
23
     * @var ResponseList $responses
24
     */
25
    private ResponseList $responses;
26
27
    /**
28
     * ParallelProcessor constructor.
29
     * @param array $config
30
     */
31
    public function __construct(array $config)
32
    {
33
        $this->clear();
34
        $this->config = $config;
35
    }
36
37
    /**
38
     * @param string $label
39
     * @param Closure $closure
40
     * @return ParallelProcessor
41
     */
42
    public function add(string $label, Closure $closure)
43
    {
44
        $this->processes[] = new Process($this->config['artisan_path'], new ProcessHandler($label, $closure));
45
        return $this;
46
    }
47
48
    /**
49
     * @return void
50
     */
51
    public function run()
52
    {
53
        $this->runProcesses();
54
        $this->clear();
55
    }
56
57
    /**
58
     * @return ResponseList
59
     */
60
    public function wait()
61
    {
62
        $this->runProcesses();
63
        $this->fetchResults();
64
        $responses = $this->responses;
65
        $this->clear();
66
        return $responses;
67
    }
68
69
    /**
70
     * @return void
71
     */
72
    private function clear()
73
    {
74
        $this->processes = [];
75
        $this->responses = new ResponseList([]);
76
    }
77
78
    /**
79
     * @return void
80
     */
81
    private function runProcesses(): void
82
    {
83
        foreach ($this->processes as $process) {
84
            $process->start();
85
        }
86
    }
87
88
    /**
89
     * @return void
90
     */
91
    private function fetchResults(): void
92
    {
93
        while (count($this->processes)) {
94
            foreach ($this->processes as $index => $process) {
95
                if (!$process->isRunning()) {
96
                    unset($this->processes[$index]);
97
                    $this->responses->add($process);
98
                }
99
            }
100
        }
101
    }
102
}
103