Files
kiri-http-server/Abstracts/HotReload.php
T
2024-11-18 16:59:10 +08:00

183 lines
3.4 KiB
PHP

<?php
namespace Kiri\Server\Abstracts;
use Kiri\Di\Inject\Container;
use Kiri\Error\StdoutLogger;
use Kiri\Server\ServerInterface;
use Psr\Log\LoggerInterface;
use Swoole\Event;
use Swoole\Process;
use Kiri\Server\Processes\AbstractProcess;
class HotReload extends AbstractProcess
{
/**
* @var mixed
*/
protected mixed $pipe;
/**
* @var LoggerInterface|StdoutLogger
*/
#[Container(LoggerInterface::class)]
public StdoutLogger|LoggerInterface $logger;
/**
* @var bool
*/
protected bool $enable_coroutine = false;
/**
* @var array
*/
protected array $watches = [];
/**
* @var bool
*/
protected bool $enable_queue = false;
/**
* @var bool
*/
protected bool $reloading = false;
/**
* @return string
*/
public function getName(): string
{
return 'hotReload.process';
}
/**
* @return void
*/
public function onSigterm(): void
{
// TODO: Implement onSigterm() method.
$this->stop();
}
/**
* @param ?Process $process
*/
public function process(Process|null $process): void
{
$this->pipe = inotify_init();
$this->addListen();
Event::add($this->pipe, function () use ($process) {
$read = inotify_read($this->pipe);
var_dump($read);
$this->reload();
});
Event::cycle(function (): void {
if ($this->isStop()) {
Event::exit();
}
});
Event::wait();
}
/**
* @return void
*/
public function reload(): void
{
if ($this->reloading) {
return;
}
$this->reloading = true;
$this->clear();
di(ServerInterface::class)->reload();
$this->addListen();
$this->reloading = false;
var_dump(inotify_queue_len($this->pipe));
}
/**
* @return void
*/
protected function addListen(): void
{
foreach (config('reload.listen') as $value) {
$this->readDirectory($value);
}
}
/**
* @return void
*/
protected function clear(): void
{
$this->watches = [];
}
/**
* @param string $directory
* @return void
*/
public function readFile(string $directory): void
{
if (str_ends_with($directory, '.php') === true) {
$wd = inotify_add_watch($this->pipe, $directory, IN_MODIFY | IN_MOVE | IN_CREATE | IN_DELETE);
$this->watches[] = $wd;
}
}
/**
* @param int $directory
* @return void
*/
public function reWatch(int $directory): void
{
if (isset($this->watches[$directory])) {
inotify_rm_watch($this->pipe, $directory);
$path = $this->watches[$directory];
unset($this->watches[$directory]);
$data = inotify_add_watch($this->pipe, $path, IN_MODIFY | IN_MOVE | IN_CREATE | IN_DELETE);
$this->watches[$data] = $path;
}
}
/**
* @param string $directory
* @return void
*/
public function readDirectory(string $directory): void
{
foreach (glob($directory . '/*') as $data) {
if (is_dir($data)) {
$this->readDirectory($data);
} else {
$this->readFile($data);
}
}
}
}