Passed
Pull Request — master (#9)
by Shinji
01:54
created

DispatchTable::updateTargets()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 15
c 1
b 0
f 1
nc 3
nop 1
dl 0
loc 18
rs 9.7666
1
<?php
2
3
/**
4
 * This file is part of the sj-i/php-profiler package.
5
 *
6
 * (c) sji <[email protected]>
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
declare(strict_types=1);
13
14
namespace PhpProfiler\Inspector\Daemon\Dispatcher;
15
16
use PhpProfiler\Inspector\Daemon\Reader\Context\PhpReaderContext;
17
use PhpProfiler\Inspector\Settings\GetTraceSettings;
18
use PhpProfiler\Inspector\Settings\TargetPhpSettings;
19
use PhpProfiler\Inspector\Settings\TraceLoopSettings;
20
21
final class DispatchTable
22
{
23
    private WorkerPool $worker_pool;
24
    private TargetProcessList $assigned;
25
    private TargetPhpSettings $target_php_settings;
26
    private TraceLoopSettings $trace_loop_settings;
27
    private GetTraceSettings $get_trace_settings;
28
    /** @var array<int, PhpReaderContext> */
29
    private array $dispatch_table = [];
30
31
    public function __construct(
32
        WorkerPool $worker_pool,
33
        TargetPhpSettings $target_php_settings,
34
        TraceLoopSettings $trace_loop_settings,
35
        GetTraceSettings $get_trace_settings
36
    ) {
37
        $this->worker_pool = $worker_pool;
38
        $this->target_php_settings = $target_php_settings;
39
        $this->trace_loop_settings = $trace_loop_settings;
40
        $this->get_trace_settings = $get_trace_settings;
41
        $this->assigned = new TargetProcessList();
42
    }
43
44
    public function updateTargets(TargetProcessList $update): void
45
    {
46
        $diff = $this->assigned->getDiff($update);
47
        $this->release($diff);
48
        $this->assigned = $this->assigned->getDiff($diff);
49
        $unassigned_new = $update->getDiff($this->assigned);
50
        for ($worker = $this->worker_pool->getFreeWorker(); $worker; $worker = $this->worker_pool->getFreeWorker()) {
51
            $picked = $unassigned_new->pickOne();
52
            if (is_null($picked)) {
53
                break;
54
            }
55
            $this->assigned->putOne($picked);
56
            $this->dispatch_table[$picked] = $worker;
57
            $worker->sendSettings([
58
                $picked,
59
                $this->target_php_settings,
60
                $this->trace_loop_settings,
61
                $this->get_trace_settings
62
            ]);
63
        }
64
    }
65
66
    public function release(TargetProcessList $targets): void
67
    {
68
        foreach ($targets->getArray() as $pid) {
69
            $this->dispatch_table[$pid]->sendQuit();
70
            unset($this->dispatch_table[$pid]);
71
        }
72
    }
73
}
74