Skip to content

Instantly share code, notes, and snippets.

@leocavalcante
Created February 21, 2019 20:45
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save leocavalcante/55e92d33cd53c9e24cd41d8006d958b6 to your computer and use it in GitHub Desktop.
Save leocavalcante/55e92d33cd53c9e24cd41d8006d958b6 to your computer and use it in GitHub Desktop.
Watch script for Swoole HTTP server restarts.
<?php declare(strict_types=1);
require_once __DIR__.'/vendor/autoload.php';
use Symfony\Component\Process\Process;
$process = new Process(['php', 'index.php']);
echo "Starting process\n";
$process->start();
$files = php_files();
$watch = array_combine($files, array_map('file_hash', $files));
$count = count($watch);
echo "Watching $count files...\n";
while (true) {
sleep(2);
foreach ($watch as $pathname => $currrent_hash) {
$new_hash = file_hash($pathname);
if ($new_hash != $currrent_hash) {
echo "Change detected. Restarting process.\n";
$process->stop();
$watch[$pathname] = $new_hash;
echo "::: 🚀 :::\n";
$process->start();
continue;
}
}
}
function php_files(): array
{
$directory = new RecursiveDirectoryIterator(__DIR__);
$filter = new Filter($directory);
$iterator = new RecursiveIteratorIterator($filter);
return array_map(function ($fileInfo) {
return $fileInfo->getPathname();
}, iterator_to_array($iterator));
}
function file_hash(string $pathname): string
{
return md5(file_get_contents($pathname));
}
class Filter extends RecursiveFilterIterator
{
public function accept()
{
if ($this->current()->isDir()) {
return !in_array($this->current()->getFilename(), ['.git', 'vendor', '.', '..', '.phan']);
}
return preg_match('/\.php$/', $this->current()->getFilename());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment