Passed
Pull Request — master (#271)
by Bill
03:10
created

PidManager::write()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 2
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SwooleTW\Http\Server;
4
5
class PidManager
6
{
7
	/**
8
	 * @var string
9
	 */
10
	private $pidFile = '';
11
12
	public function __construct(string $pidFile)
13
	{
14
		$this->pidFile = $pidFile;
15
	}
16
17
	/**
18
	 * Write master pid and manager pid to pid file
19
	 *
20
	 * @throws \RuntimeException When $pidFile is not writable
21
	 */
22
	public function write(int $masterPid, int $managerPid): void
23
	{
24
		if (! is_writable($this->pidFile) && ! is_writable(dirname($this->pidFile))) {
25
			throw new \RuntimeException(sprintf('Pid file "%s" is not writable', $this->pidFile));
26
		}
27
28
		file_put_contents($this->pidFile, $masterPid . ',' . $managerPid);
29
	}
30
31
	/**
32
	 * Read master pid and manager pid from pid file
33
	 *
34
	 * @return string[] {
35
	 *	 @var string $masterPid
36
	 *	 @var string $managerPid
37
	 * }
38
	 */
39
	public function read(): array
40
	{
41
		$pids = [];
42
43
		if (is_readable($this->pidFile)) {
44
			$content = file_get_contents($this->pidFile);
45
			$pids = explode(',', $content);
46
		}
47
48
		return $pids;
49
	}
50
51
	/**
52
	 * Gets pid file path.
53
	 *
54
	 * @return string
55
	 */
56
	public function file()
57
	{
58
		return $this->pidFile;
59
	}
60
61
	/**
62
	 * Delete pid file
63
	 */
64
	public function delete(): bool
65
	{
66
		if (is_writable($this->pidFile)) {
67
			return unlink($this->pidFile);
68
		}
69
70
		return false;
71
	}
72
}
73