Passed
Push — master ( 277d4a...4e9b37 )
by Albert
06:50 queued 04:31
created

PidManager::write()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 2
dl 0
loc 11
rs 10
c 0
b 0
f 0
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 $pids;
62
    }
63
64
    /**
65
     * Gets pid file path.
66
     *
67
     * @return string
68
     */
69
    public function file()
70
    {
71
        return $this->pidFile;
72
    }
73
74
    /**
75
     * Delete pid file
76
     */
77
    public function delete(): bool
78
    {
79
        if (is_writable($this->pidFile)) {
80
            return unlink($this->pidFile);
81
        }
82
83
        return false;
84
    }
85
}
86