@@ -56,8 +56,14 @@ public function __invoke()
5656 {
5757 if (false !== ($ events = \inotify_read ($ this ->inotifyHandler ))) {
5858 foreach ($ events as $ event ) {
59- $ path = $ this ->watchDescriptors [$ event ['wd ' ]]['path ' ];
60- $ this ->emit ($ event ['mask ' ], array ($ path . $ event ['name ' ]));
59+ // make sure the watch descriptor assigned to this event is
60+ // still valid. removing watch descriptors via 'remove()'
61+ // implicitly sends a final event with mask IN_IGNORE set:
62+ // http://php.net/manual/en/inotify.constants.php#constant.in-ignored
63+ if (isset ($ this ->watchDescriptors [$ event ['wd ' ]])) {
64+ $ path = $ this ->watchDescriptors [$ event ['wd ' ]]['path ' ];
65+ $ this ->emit ($ event ['mask ' ], array ($ path . $ event ['name ' ]));
66+ }
6167 }
6268 }
6369 }
@@ -67,6 +73,7 @@ public function __invoke()
6773 *
6874 * @param string $path Path to the watched file or directory
6975 * @param integer $mask Bitmask of inotify constants
76+ * @return integer unique watch identifier, can be used to remove() watch later
7077 */
7178 public function add ($ path , $ mask )
7279 {
@@ -79,6 +86,28 @@ public function add($path, $mask)
7986 }
8087 $ descriptor = \inotify_add_watch ($ this ->inotifyHandler , $ path , $ mask );
8188 $ this ->watchDescriptors [$ descriptor ] = array ('path ' => $ path );
89+ return $ descriptor ;
90+ }
91+
92+ /**
93+ * remove/cancel the given watch identifier previously aquired via add()
94+ * i.e. stop watching the associated path
95+ *
96+ * @param integer $descriptor watch identifier previously returned from add()
97+ */
98+ public function remove ($ descriptor )
99+ {
100+ if (isset ($ this ->watchDescriptors [$ descriptor ])) {
101+ unset($ this ->watchDescriptors [$ descriptor ]);
102+
103+ if ($ this ->watchDescriptors ) {
104+ // there are still watch paths remaining => only remove this descriptor
105+ \inotify_rm_watch ($ this ->inotifyHandler , $ descriptor );
106+ } else {
107+ // no more paths watched => close whole handler
108+ $ this ->close ();
109+ }
110+ }
82111 }
83112
84113 /**
0 commit comments