<?php
declare(strict_types=1);
/**
* @author Maciej Kaczmarek <maciej.kaczmarek@autentika.pl>
*/
namespace Hitso\Bundle\CommonBundle\EventListener;
use Hitso\Bundle\CommonBundle\Entity\CronLog;
use Hitso\Bundle\CommonBundle\Manager\CronLogManager;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CronListener implements EventSubscriberInterface
{
/**
* @var int
*/
private $startTime;
/**
* @var CronLogManager
*/
private $manager;
/**
* @var CronLog
*/
private $log;
/**
* @var string
*/
private $env;
/**
* @var int
*/
private $ttl;
public function __construct(CronLogManager $manager, $env, $ttl)
{
$this->manager = $manager;
$this->env = $env;
$this->ttl = $ttl;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
ConsoleEvents::COMMAND => 'onCommand',
ConsoleEvents::TERMINATE => 'onCommandTerminate',
];
}
public function onCommand(ConsoleEvent $event)
{
$event->getCommand()->addOption(
'cron',
null,
InputOption::VALUE_NONE,
'Mark as CRON command and log its execution status.'
);
$input = $event->getInput();
if (!$input->hasParameterOption('--cron')) {
return;
}
$log = $this->log = $this->manager->initResource();
$log->setCommand($input->getFirstArgument());
$log->setFullCommand((string) $input);
$log->setEnv($this->env);
$log->setStartedAt(new \DateTime());
$this->manager->createResource($log);
$this->startTime = microtime(true);
}
public function onCommandTerminate(ConsoleTerminateEvent $event)
{
if (!$event->getInput()->hasOption('cron') || !$event->getInput()->getOption('cron')) {
return;
}
$time = microtime(true) - $this->startTime;
$memory = memory_get_peak_usage(true);
$this->log->setFinishedAt(new \DateTime())->setRunningTime($time)->setMemoryUsage($memory)->setExitCode(
$event->getExitCode()
);
$this->manager->updateResource($this->log);
$this->manager->getRepository()->gc($this->ttl);
$this->log = null;
$this->startTime = null;
}
}