Hoa central
Watcher.php
Go to the documentation of this file.
1 <?php
2 
37 namespace Hoa\File;
38 
39 use Hoa\Core;
40 
49 class Watcher extends Finder implements Core\Event\Listenable
50 {
56  protected $_on = null;
57 
63  protected $_latency = 1;
64 
65 
66 
73  public function __construct($latency = null)
74  {
75  parent::__construct();
76 
77  $this->_on = new Core\Event\Listener(
78  $this,
79  [
80  'new',
81  'modify',
82  'move'
83  ]
84  );
85 
86  if (null !== $latency) {
87  $this->setLatency($latency);
88  }
89 
90  return;
91  }
92 
101  public function on($listenerId, $callable)
102  {
103  $this->_on->attach($listenerId, $callable);
104 
105  return $this;
106  }
107 
118  public function run()
119  {
120  $iterator = $this->getIterator();
121  $previous = iterator_to_array($iterator);
122  $current = $previous;
123 
124  while (true) {
125  foreach ($current as $name => $c) {
126  if (!isset($previous[$name])) {
127  $this->_on->fire(
128  'new',
129  new Core\Event\Bucket([
130  'file' => $c
131  ])
132  );
133 
134  continue;
135  }
136 
137  if (null === $c->getHash()) {
138  unset($current[$name]);
139 
140  continue;
141  }
142 
143  if ($previous[$name]->getHash() != $c->getHash()) {
144  $this->_on->fire(
145  'modify',
146  new Core\Event\Bucket([
147  'file' => $c
148  ])
149  );
150  }
151 
152  unset($previous[$name]);
153  }
154 
155  foreach ($previous as $p) {
156  $this->_on->fire(
157  'move',
158  new Core\Event\Bucket([
159  'file' => $p
160  ])
161  );
162  }
163 
164  usleep($this->getLatency() * 1000000);
165 
166  $previous = $current;
167  $current = iterator_to_array($iterator);
168  }
169 
170  return;
171  }
172 
179  public function setLatency($latency)
180  {
181  $old = $this->_latency;
182  $this->_latency = $latency;
183 
184  return $old;
185  }
186 
192  public function getLatency()
193  {
194  return $this->_latency;
195  }
196 }
on($listenerId, $callable)
Definition: Watcher.php:101
setLatency($latency)
Definition: Watcher.php:179
__construct($latency=null)
Definition: Watcher.php:73