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