1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Webparking\QueueEnsurer\PidsFile; |
4
|
|
|
|
5
|
|
|
class ContentsManager |
6
|
|
|
{ |
7
|
|
|
private const PIDS_FILE_NAME = 'app/queue-listener-pids.json'; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* @return string[] |
11
|
|
|
*/ |
12
|
7 |
|
public function getQueueNames(): array |
13
|
|
|
{ |
14
|
7 |
|
return array_keys($this->getFileContents()); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
/** @return int[] */ |
18
|
7 |
|
public function getPids(string $queueName): array |
19
|
|
|
{ |
20
|
7 |
|
$fileContents = $this->getFileContents(); |
21
|
|
|
|
22
|
7 |
|
if (!isset($fileContents[$queueName])) { |
23
|
3 |
|
return []; |
24
|
|
|
} |
25
|
|
|
|
26
|
5 |
|
return $fileContents[$queueName]; |
27
|
|
|
} |
28
|
|
|
|
29
|
3 |
|
public function addPid(string $queueName, int $processId): void |
30
|
|
|
{ |
31
|
3 |
|
$pids = $this->getPids($queueName); |
32
|
|
|
|
33
|
3 |
|
$pids[] = $processId; |
34
|
|
|
|
35
|
3 |
|
$this->updateFileForQueue($queueName, $pids); |
36
|
3 |
|
} |
37
|
|
|
|
38
|
3 |
|
public function removePid(string $queueName, int $processId): void |
39
|
|
|
{ |
40
|
3 |
|
$pids = $this->getPids($queueName); |
41
|
|
|
|
42
|
3 |
|
unset($pids[array_search($processId, $pids)]); |
43
|
|
|
|
44
|
3 |
|
$this->updateFileForQueue($queueName, $pids); |
45
|
3 |
|
} |
46
|
|
|
|
47
|
1 |
|
public function removeQueue(string $queueName): void |
48
|
|
|
{ |
49
|
1 |
|
$fileContents = $this->getFileContents(); |
50
|
|
|
|
51
|
1 |
|
unset($fileContents[$queueName]); |
52
|
|
|
|
53
|
1 |
|
$this->writeFile($fileContents); |
54
|
1 |
|
} |
55
|
|
|
|
56
|
|
|
/** @param array<int> $contents */ |
57
|
6 |
|
private function updateFileForQueue(string $queueName, array $contents): void |
58
|
|
|
{ |
59
|
6 |
|
$fileContents = $this->getFileContents(); |
60
|
|
|
|
61
|
6 |
|
$fileContents[$queueName] = $contents; |
62
|
|
|
|
63
|
6 |
|
$this->writeFile($fileContents); |
64
|
6 |
|
} |
65
|
|
|
|
66
|
|
|
/** @return array<string, array<int>> */ |
67
|
7 |
|
private function getFileContents(): array |
68
|
|
|
{ |
69
|
7 |
|
if (!file_exists($this->getPidsFilePath())) { |
70
|
1 |
|
return []; |
71
|
|
|
} |
72
|
|
|
|
73
|
6 |
|
return json_decode( |
74
|
6 |
|
(string) file_get_contents($this->getPidsFilePath()), |
75
|
6 |
|
true |
76
|
|
|
); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** @param array<string, array<int>> $contents */ |
80
|
6 |
|
private function writeFile(array $contents): void |
81
|
|
|
{ |
82
|
6 |
|
file_put_contents( |
83
|
6 |
|
$this->getPidsFilePath(), |
84
|
6 |
|
json_encode($contents) |
85
|
|
|
); |
86
|
6 |
|
} |
87
|
|
|
|
88
|
7 |
|
private function getPidsFilePath(): string |
89
|
|
|
{ |
90
|
7 |
|
return storage_path(self::PIDS_FILE_NAME); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|