1 | <?php |
||
16 | class NotifyHandler implements INotifyHandler { |
||
17 | /** |
||
18 | * @var Connection |
||
19 | */ |
||
20 | private $connection; |
||
21 | |||
22 | /** |
||
23 | * @var string |
||
24 | */ |
||
25 | private $path; |
||
26 | |||
27 | private $listening = true; |
||
28 | |||
29 | // see error.h |
||
30 | const EXCEPTION_MAP = [ |
||
31 | ErrorCodes::RevisionMismatch => RevisionMismatchException::class, |
||
32 | ]; |
||
33 | |||
34 | /** |
||
35 | * @param Connection $connection |
||
36 | * @param string $path |
||
37 | */ |
||
38 | 20 | public function __construct(Connection $connection, $path) { |
|
39 | 20 | $this->connection = $connection; |
|
40 | 20 | $this->path = $path; |
|
41 | 20 | } |
|
42 | |||
43 | /** |
||
44 | * Get all changes detected since the start of the notify process or the last call to getChanges |
||
45 | * |
||
46 | * @return Change[] |
||
47 | */ |
||
48 | 16 | public function getChanges() { |
|
49 | 16 | if (!$this->listening) { |
|
50 | 4 | return []; |
|
51 | } |
||
52 | 12 | stream_set_blocking($this->connection->getOutputStream(), 0); |
|
53 | 12 | $lines = []; |
|
54 | 12 | while (($line = $this->connection->readLine())) { |
|
55 | 12 | $this->checkForError($line); |
|
56 | 12 | $lines[] = $line; |
|
57 | 3 | } |
|
58 | 12 | stream_set_blocking($this->connection->getOutputStream(), 1); |
|
59 | 12 | return array_values(array_filter(array_map([$this, 'parseChangeLine'], $lines))); |
|
60 | } |
||
61 | |||
62 | /** |
||
63 | * Listen actively to all incoming changes |
||
64 | * |
||
65 | * Note that this is a blocking process and will cause the process to block forever if not explicitly terminated |
||
66 | * |
||
67 | * @param callable $callback |
||
68 | */ |
||
69 | 8 | public function listen($callback) { |
|
70 | 8 | if ($this->listening) { |
|
71 | 8 | $this->connection->read(function ($line) use ($callback) { |
|
72 | 8 | $this->checkForError($line); |
|
73 | 8 | $change = $this->parseChangeLine($line); |
|
74 | 8 | if ($change) { |
|
75 | 8 | return $callback($change); |
|
76 | } |
||
77 | 8 | }); |
|
78 | 2 | } |
|
79 | 8 | } |
|
80 | |||
81 | 16 | private function parseChangeLine($line) { |
|
93 | |||
94 | 16 | private function checkForError($line) { |
|
95 | 16 | if (substr($line, 0, 16) === 'notify returned ') { |
|
96 | $error = substr($line, 16); |
||
100 | |||
101 | 20 | public function stop() { |
|
105 | |||
106 | 20 | public function __destruct() { |
|
109 | } |
||
110 |