src/EventListener/RunCommandListener.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpKernel\Event\TerminateEvent;
  4. class RunCommandListener
  5. {
  6.     /**
  7.      * @var string
  8.      */
  9.     public const ATTR_COMMAND 'tmb.cmd';
  10.     /**
  11.      * @var string
  12.      */
  13.     private $dir;
  14.     /**
  15.      * RunCommandListener constructor.
  16.      *
  17.      * @param string $dir
  18.      */
  19.     public function __construct(string $dir)
  20.     {
  21.         $this->dir $dir;
  22.     }
  23.     /**
  24.      * @param TerminateEvent $event
  25.      */
  26.     public function onKernelTerminate(TerminateEvent $event): void
  27.     {
  28.         if (! $event->isMasterRequest()) {
  29.             return;
  30.         }
  31.         $request $event->getRequest();
  32.         if (! $request->attributes->has(self::ATTR_COMMAND)) {
  33.             return;
  34.         }
  35.         $cmd $request->attributes->get(self::ATTR_COMMAND);
  36.         if (empty($cmd)) {
  37.             return;
  38.         }
  39.         $this->runInBackground((string) $cmd);
  40.     }
  41.     /**
  42.      * @param string $cmd
  43.      */
  44.     protected function runInBackground(string $cmd): void
  45.     {
  46.         $noHupCommand sprintf('bash -c "exec nohup setsid %s/bin/console %s > /dev/null 2>&1 &"',
  47.             $this->dir,
  48.             $cmd
  49.         );
  50.         exec($noHupCommand);
  51.     }
  52. }