|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @copyright Copyright (c) 2016 Robin Appelman <[email protected]> |
|
4
|
|
|
* This file is licensed under the Licensed under the MIT license: |
|
5
|
|
|
* http://opensource.org/licenses/MIT |
|
6
|
|
|
* |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Icewind\SMB; |
|
10
|
|
|
|
|
11
|
|
|
|
|
12
|
|
|
class NotifyHandler implements INotifyHandler { |
|
13
|
|
|
/** |
|
14
|
|
|
* @var Connection |
|
15
|
|
|
*/ |
|
16
|
|
|
private $connection; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @var string |
|
20
|
|
|
*/ |
|
21
|
|
|
private $path; |
|
22
|
|
|
|
|
23
|
|
|
private $listening = true; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @param Connection $connection |
|
27
|
|
|
* @param string $path |
|
28
|
|
|
*/ |
|
29
|
|
|
public function __construct(Connection $connection, $path) { |
|
30
|
|
|
$this->connection = $connection; |
|
31
|
|
|
$this->path = $path; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Get all changes detected since the start of the notify process or the last call to getChanges |
|
36
|
|
|
* |
|
37
|
|
|
* @return Change[] |
|
38
|
|
|
*/ |
|
39
|
|
|
public function getChanges() { |
|
40
|
|
|
if (!$this->listening) { |
|
41
|
|
|
return []; |
|
42
|
|
|
} |
|
43
|
|
|
stream_set_blocking($this->connection->getOutputStream(), 0); |
|
44
|
|
|
$lines = []; |
|
45
|
|
|
while (($line = $this->connection->readLine())) { |
|
46
|
|
|
$lines[] = $line; |
|
47
|
|
|
} |
|
48
|
|
|
stream_set_blocking($this->connection->getOutputStream(), 1); |
|
49
|
|
|
return array_values(array_filter(array_map([$this, 'parseChangeLine'], $lines))); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Listen actively to all incoming changes |
|
54
|
|
|
* |
|
55
|
|
|
* Note that this is a blocking process and will cause the process to block forever if not explicitly terminated |
|
56
|
|
|
* |
|
57
|
|
|
* @param callable $callback |
|
58
|
|
|
*/ |
|
59
|
|
|
public function listen($callback) { |
|
60
|
|
|
if ($this->listening) { |
|
61
|
|
|
$this->connection->read(function ($line) use ($callback) { |
|
62
|
|
|
return $callback($this->parseChangeLine($line)); |
|
63
|
|
|
}); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
private function parseChangeLine($line) { |
|
68
|
|
|
$code = (int)substr($line, 0, 4); |
|
69
|
|
|
if ($code === 0) { |
|
70
|
|
|
return null; |
|
71
|
|
|
} |
|
72
|
|
|
$subPath = str_replace('\\', '/', substr($line, 5)); |
|
73
|
|
|
if ($this->path === '') { |
|
74
|
|
|
return new Change($code, $subPath); |
|
75
|
|
|
} else { |
|
76
|
|
|
return new Change($code, $this->path . '/' . $subPath); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
public function stop() { |
|
81
|
|
|
$this->listening = false; |
|
82
|
|
|
$this->connection->close(); |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
public function __destruct() { |
|
86
|
|
|
$this->stop(); |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|