Passed
Pull Request — 0.6.x (#198)
by Shinji
01:39
created

TargetProcessList::removeByPid()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 3
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
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 function array_rand;
17
use function array_udiff;
18
19
final class TargetProcessList implements TargetProcessListInterface
20
{
21
    /** @var TargetProcessDescriptor[] */
22
    private array $process_list;
23
24
    public function __construct(TargetProcessDescriptor ...$process_list)
25
    {
26
        $this->process_list = $process_list;
27
    }
28
29
    public function pickOne(): ?TargetProcessDescriptor
30
    {
31
        if ($this->process_list === []) {
32
            return null;
33
        }
34
        $key = array_rand($this->process_list);
35
        $value = $this->process_list[$key];
36
        unset($this->process_list[$key]);
37
        return $value;
38
    }
39
40
    public function putOne(TargetProcessDescriptor $process_descriptor): void
41
    {
42
        $this->process_list[] = $process_descriptor;
43
    }
44
45
    public function getDiff(TargetProcessListInterface $compare_list): self
46
    {
47
        /** @var TargetProcessDescriptor[] $diff */
48
        $diff = array_udiff(
49
            $this->process_list,
50
            $compare_list->getArray(),
51
            fn (TargetProcessDescriptor $a, TargetProcessDescriptor $b) => $a <=> $b,
52
        );
53
        return new self(
54
            ...$diff
55
        );
56
    }
57
58
    /** @return TargetProcessDescriptor[] */
59
    public function getArray(): array
60
    {
61
        return $this->process_list;
62
    }
63
64
    public function removeByPid(int $pid): void
65
    {
66
        foreach ($this->process_list as $key => $process_descriptor) {
67
            if ($process_descriptor->pid === $pid) {
68
                unset($this->process_list[$key]);
69
            }
70
        }
71
    }
72
}
73