Files
oficial/cli/src/Service/Schedule.php
aldarien 307f2ac7d7 feature/cierres (#25)
Varios cambios

Co-authored-by: Juan Pablo Vial <jpvialb@incoviba.cl>
Reviewed-on: #25
2025-07-22 13:18:00 +00:00

67 lines
2.3 KiB
PHP

<?php
namespace Incoviba\Service;
use Cron\CronExpression;
use DateTimeInterface;
use DateTimeImmutable;
use Psr\Log\LoggerInterface;
use Throwable;
class Schedule
{
public function __construct(protected LoggerInterface $logger) {}
protected string $filename = '/var/spool/cron/crontabs/root';
public function getPending(): array
{
$now = new DateTimeImmutable();
$schedule = $this->getCommandList();
$commands = [];
foreach ($schedule as $line) {
$line = trim($line);
if (trim($line) === '' or str_starts_with($line, '#')) {
continue;
}
try {
$data = $this->parseCommandLine($line);
} catch (Throwable $exception) {
$this->logger->error($exception->getMessage(), ['line' => $line, 'exception' => $exception]);
continue;
}
if ($this->processSchedule($now, $data)) {
$commands[] = $data['command'];
}
}
return $commands;
}
protected function getCommandList(): array
{
if (!file_exists($this->filename)) {
return [];
}
return explode("\n", file_get_contents($this->filename));
}
protected function parseCommandLine(string $line): array
{
$regex = '/^(?<minutes>(\d{1,2}|\*|\*\/\d{1,2})?) (?<hours>(\d{1,2}|\*|\*\/\d{1,2})?) (?<day_month>(\d{1,2}|\*|\*\/\d{1,2})?) (?<month>(\d{1,2}|\*|\*\/\d{1,2})?) (?<day_week>(\d{1,2}|\*|\*\/\d{1,2})?) (?<command>.*)$/';
preg_match_all($regex, $line, $matches);
return [
'minutes' => $matches['minutes'][0],
'hours' => $matches['hours'][0],
'day_month' => $matches['day_month'][0],
'month' => $matches['month'][0],
'day_week' => $matches['day_week'][0],
'command' => trim(str_replace(['/code/bin/incoviba', '>> /logs/commands 2>&1'], '', $matches['command'][0])),
];
}
protected function processSchedule(DateTimeInterface $now, array $schedule): bool
{
$cronLine = "{$schedule['minutes']} {$schedule['hours']} {$schedule['day_month']} {$schedule['month']} {$schedule['day_week']}";
$cron = new CronExpression($cronLine);
return $cron->isDue($now);
}
}