Completed
Push — master ( cfa673...036dbf )
by Robin
07:03
created

NotifyHandler::listen()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 2
nop 1
crap 3
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 15
	public function __construct(Connection $connection, $path) {
30 15
		$this->connection = $connection;
31 15
		$this->path = $path;
32 15
	}
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 12
	public function getChanges() {
40 12
		if (!$this->listening) {
41 3
			return [];
42
		}
43 9
		stream_set_blocking($this->connection->getOutputStream(), 0);
44 9
		$lines = [];
45 9
		while (($line = $this->connection->readLine())) {
46 9
			$lines[] = $line;
47 9
		}
48 9
		stream_set_blocking($this->connection->getOutputStream(), 1);
49 9
		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 5
	public function listen($callback) {
60 5
		if ($this->listening) {
61 3
			$this->connection->read(function ($line) use ($callback) {
62 3
				$change = $this->parseChangeLine($line);
63 3
				if ($change) {
64 3
					return $callback($change);
65
				}
66 3
			});
67 3
		}
68 5
	}
69
70 12
	private function parseChangeLine($line) {
71 12
		$code = (int)substr($line, 0, 4);
72 12
		if ($code === 0) {
73 9
			return null;
74
		}
75 12
		$subPath = str_replace('\\', '/', substr($line, 5));
76 12
		if ($this->path === '') {
77 9
			return new Change($code, $subPath);
78
		} else {
79 3
			return new Change($code, $this->path . '/' . $subPath);
80
		}
81
	}
82
83 15
	public function stop() {
84 15
		$this->listening = false;
85 15
		$this->connection->close();
86 15
	}
87
88 15
	public function __destruct() {
89 15
		$this->stop();
90 15
	}
91
}
92