php-spark/plugins/com.noccy.watcher/Monitor/MtimeMonitor.php

78 lines
1.7 KiB
PHP

<?php
namespace SparkPlug\Com\Noccy\Watcher\Monitor;
use SparkPlug\Com\Noccy\Watcher\Rule;
class MtimeMonitor implements MonitorInterface
{
private array $rules = [];
private array $watched = [];
private array $modified = [];
/**
* {@inheritDoc}
*/
public function add(Rule $rule)
{
$this->rules[] = $rule;
}
/**
* {@inheritDoc}
*/
public function getModified(): array
{
$mod = $this->modified;
$this->modified = [];
return $mod;
}
/**
* {@inheritDoc}
*/
public function getWatched(): array
{
return [];
}
public function loop()
{
foreach ($this->rules as $rule) {
$this->checkRule($rule);
}
}
private function checkRule(Rule $rule)
{
clearstatcache();
$paths = $rule->getWatchedFiles();
$check = [];
foreach ($paths as $path) {
if (str_contains($path, '*')) {
$check = array_merge($check, glob($path));
} else {
$check[] = $path;
}
}
foreach ($check as $path) {
if (empty($this->watched[$path])) {
$this->watched[$path] = filemtime($path);
} else {
$mtime = filemtime($path);
if ($mtime > $this->watched[$path]) {
printf("* modified: %s (%s)\n", $path, $rule->getName());
$this->watched[$path] = $mtime;
if (!in_array($rule, $this->modified)) {
$this->modified[] = $rule;
}
}
}
}
}
}