PidManager   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 22
c 2
b 0
f 0
dl 0
loc 82
rs 10
wmc 11

6 Methods

Rating   Name   Duplication   Size   Complexity  
A setPidFile() 0 5 1
A __construct() 0 4 2
A delete() 0 7 2
A write() 0 11 3
A file() 0 3 1
A read() 0 12 2
1
<?php
2
3
namespace SwooleTW\Http\Server;
4
5
class PidManager
6
{
7
    protected $pidFile;
8
9
    public function __construct(string $pidFile = null)
10
    {
11
        $this->setPidFile(
12
            $pidFile ?: sys_get_temp_dir() . '/swoole.pid'
13
        );
14
    }
15
16
    /**
17
     * Set pid file path
18
     */
19
    public function setPidFile(string $pidFile): self
20
    {
21
        $this->pidFile = $pidFile;
22
23
        return $this;
24
    }
25
26
    /**
27
     * Write master pid and manager pid to pid file
28
     *
29
     * @throws \RuntimeException when $pidFile is not writable
30
     */
31
    public function write(int $masterPid, int $managerPid): void
32
    {
33
        if (! is_writable($this->pidFile)
34
            && ! is_writable(dirname($this->pidFile))
35
        ) {
36
            throw new \RuntimeException(
37
                sprintf('Pid file "%s" is not writable', $this->pidFile)
38
            );
39
        }
40
41
        file_put_contents($this->pidFile, $masterPid . ',' . $managerPid);
42
    }
43
44
    /**
45
     * Read master pid and manager pid from pid file
46
     *
47
     * @return string[] {
48
     *   @var string $masterPid
49
     *   @var string $managerPid
50
     * }
51
     */
52
    public function read(): array
53
    {
54
        $pids = [];
55
56
        if (is_readable($this->pidFile)) {
57
            $content = file_get_contents($this->pidFile);
58
            $pids = explode(',', $content);
59
        }
60
61
        return [
62
            'masterPid' => $pids[0] ?? null,
63
            'managerPid' => $pids[1] ?? null
64
        ];
65
    }
66
67
    /**
68
     * Gets pid file path.
69
     *
70
     * @return string
71
     */
72
    public function file()
73
    {
74
        return $this->pidFile;
75
    }
76
77
    /**
78
     * Delete pid file
79
     */
80
    public function delete(): bool
81
    {
82
        if (is_writable($this->pidFile)) {
83
            return unlink($this->pidFile);
84
        }
85
86
        return false;
87
    }
88
}
89