| Total Complexity | 11 |
| Total Lines | 82 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 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 |
||
| 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 |
||
| 87 | } |
||
| 88 | } |
||
| 89 |