<?php
namespace App\EventSubscriber\SchoolYear;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Command\SchoolYear\SchoolYearClone;
use App\Entity\SchoolYear\SchoolYear;
use Exception;
use JetBrains\PhpStorm\ArrayShape;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Process\Process;
class SchoolYearSubscriber implements EventSubscriberInterface
{
public function __construct(
private KernelInterface $kernel,
private LoggerInterface $logger,
)
{
}
#[ArrayShape([KernelEvents::VIEW => "array"])]
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['duplicate', EventPriorities::POST_WRITE],
];
}
/**
* @throws Exception
*/
public function duplicate(ViewEvent $event): void
{
$schoolYear = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$schoolYear instanceof SchoolYear || Request::METHOD_POST !== $method) {
return;
}
$pathToBin = $this->kernel->getProjectDir() . '/bin/console';
foreach (SchoolYearClone::ORDERED_PART_TO_CLONE as $part) {
$cmd = 'php ' . $pathToBin . ' ' . SchoolYearClone::DEFAULT_NAME . ' ' . $schoolYear->getId() . ' ' . $schoolYear->getSchoolYearToDuplicate()->getId() . ' ' . $part;
$process = Process::fromShellCommandline($cmd);
$process->setTimeout(10000);
$process->start();
$process->wait(
function ($type, $buffer) use ($process) {
if($type === Process::ERR && !str_contains($buffer, '[debug]')){
$this->logger->error($process->getCommandLine() . " :\n" . $buffer);
}
}
);
}
}
}