1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Inotify; |
6
|
|
|
|
7
|
|
|
use Generator; |
8
|
|
|
use InvalidArgumentException; |
9
|
|
|
|
10
|
|
|
class InotifyProxy implements InotifyProxyInterface |
11
|
|
|
{ |
12
|
|
|
private $inotify; |
13
|
|
|
/** |
14
|
|
|
* @var WatchedResource[] |
15
|
|
|
*/ |
16
|
|
|
private array $watchedResources; |
17
|
|
|
|
18
|
2 |
|
public function __construct() |
19
|
|
|
{ |
20
|
2 |
|
$this->inotify = inotify_init(); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @return Generator|InotifyEvent[] |
25
|
|
|
*/ |
26
|
2 |
|
public function read(): Generator |
27
|
|
|
{ |
28
|
2 |
|
$events = inotify_read($this->inotify); |
29
|
2 |
|
if (false !== $events) { |
30
|
2 |
|
foreach ($events as $event) { |
31
|
2 |
|
$event = new InotifyEvent( |
32
|
2 |
|
$event['wd'], |
33
|
2 |
|
InotifyEventCodeEnum::createFromMask($event['mask']), |
34
|
2 |
|
$event['cookie'], |
35
|
2 |
|
$event['name'], |
36
|
2 |
|
$this->watchedResources[$event['wd']], |
37
|
2 |
|
time() |
38
|
2 |
|
); |
39
|
|
|
|
40
|
|
|
// if file is removed we need clean watchedResources |
41
|
2 |
|
if ($event->getInotifyEventCode() === InotifyEventCodeEnum::ON_IGNORED()->getValue()) { |
42
|
1 |
|
unset($this->watchedResources[$event->getId()]); |
43
|
|
|
} |
44
|
|
|
|
45
|
2 |
|
yield $event; |
46
|
|
|
} |
47
|
|
|
} |
48
|
2 |
|
unset($events); |
49
|
|
|
} |
50
|
|
|
|
51
|
2 |
|
public function addWatch(WatchedResource $watchedResource): void |
52
|
|
|
{ |
53
|
2 |
|
if (!is_readable($watchedResource->getPathname())) { |
54
|
|
|
throw new InvalidArgumentException('Resource not exists: "' . $watchedResource->getPathname() . '""'); |
55
|
|
|
} |
56
|
|
|
|
57
|
2 |
|
$id = inotify_add_watch( |
58
|
2 |
|
$this->inotify, |
59
|
2 |
|
$watchedResource->getPathname(), |
60
|
2 |
|
$watchedResource->getWatchOnChangeFlags() |
61
|
2 |
|
); |
62
|
|
|
|
63
|
2 |
|
$this->watchedResources[$id] = $watchedResource; |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
public function closeWatchers(): void |
67
|
|
|
{ |
68
|
2 |
|
foreach ($this->watchedResources as $id => $resource) { |
69
|
1 |
|
inotify_rm_watch($this->inotify, $id); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function havePendingEvents(): bool |
74
|
|
|
{ |
75
|
|
|
return inotify_queue_len($this->inotify) > 1; |
76
|
|
|
} |
77
|
|
|
|
78
|
2 |
|
public function __destruct() |
79
|
|
|
{ |
80
|
2 |
|
if (is_resource($this->inotify)) { |
81
|
2 |
|
fclose($this->inotify); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
} |