Completed
Push — master ( 1bf43b...c1afd7 )
by Robin
01:56
created

NotifyHandler   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 2
dl 0
loc 77
ccs 36
cts 36
cp 1
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getChanges() 0 12 3
A listen() 0 7 2
A parseChangeLine() 0 12 3
A stop() 0 4 1
A __destruct() 0 3 1
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 8
	public function __construct(Connection $connection, $path) {
30 8
		$this->connection = $connection;
31 8
		$this->path = $path;
32 8
	}
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 6
	public function getChanges() {
40 6
		if (!$this->listening) {
41 2
			return [];
42
		}
43 4
		stream_set_blocking($this->connection->getOutputStream(), 0);
44 4
		$lines = [];
45 4
		while (($line = $this->connection->readLine())) {
46 4
			$lines[] = $line;
47 2
		}
48 4
		stream_set_blocking($this->connection->getOutputStream(), 1);
49 4
		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 2
	public function listen($callback) {
60 2
		if ($this->listening) {
61 2
			$this->connection->read(function ($line) use ($callback) {
62 2
				return $callback($this->parseChangeLine($line));
63 2
			});
64 1
		}
65 2
	}
66
67 6
	private function parseChangeLine($line) {
68 6
		$code = (int)substr($line, 0, 4);
69 6
		if ($code === 0) {
70 4
			return null;
71
		}
72 6
		$subPath = str_replace('\\', '/', substr($line, 5));
73 6
		if ($this->path === '') {
74 4
			return new Change($code, $subPath);
75
		} else {
76 2
			return new Change($code, $this->path . '/' . $subPath);
77
		}
78
	}
79
80 8
	public function stop() {
81 8
		$this->listening = false;
82 8
		$this->connection->close();
83 8
	}
84
85 8
	public function __destruct() {
86 8
		$this->stop();
87 8
	}
88
}
89