src/Messenger/EventListener/WorkersRegistryEventListener.php line 72

Open in your IDE?
  1. <?php
  2. /**
  3.  * Copyright (c) 2011-present Qualiteam software Ltd. All rights reserved.
  4.  * See https://www.x-cart.com/license-agreement.html for license details.
  5.  */
  6. namespace XCart\Messenger\EventListener;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\Filesystem\Filesystem;
  9. use Symfony\Component\Messenger\Event\WorkerRunningEvent;
  10. use Symfony\Component\Messenger\Event\WorkerStartedEvent;
  11. use Symfony\Component\Messenger\Event\WorkerStoppedEvent;
  12. use XCart\Messenger\Event\WorkerPingEvent;
  13. final class WorkersRegistryEventListener implements EventSubscriberInterface
  14. {
  15.     private Filesystem $filesystem;
  16.     private string $workersPoolPath;
  17.     /**
  18.      * @var false|int
  19.      */
  20.     private $pid;
  21.     public function __construct(Filesystem $filesystemstring $workersPoolPath)
  22.     {
  23.         $this->filesystem $filesystem;
  24.         $this->workersPoolPath $workersPoolPath;
  25.         $this->pid getmypid();
  26.     }
  27.     /**
  28.      * @return array<string, string>
  29.      */
  30.     public static function getSubscribedEvents()
  31.     {
  32.         return [
  33.             WorkerStartedEvent::class => 'onWorkerStarted',
  34.             WorkerStoppedEvent::class => 'onWorkerStopped',
  35.             WorkerRunningEvent::class => 'onWorkerRunning',
  36.             WorkerPingEvent::class    => 'onWorkerPing',
  37.         ];
  38.     }
  39.     public function onWorkerStarted(): void
  40.     {
  41.         $this->dumpWorkerFile();
  42.         if (function_exists('pcntl_signal')) {
  43.             pcntl_signal(\SIGINT, function () {
  44.                 $this->onWorkerStopped();
  45.                 // We should only write remove our flag and exit, should not resume execution or wait for graceful stop
  46.                 exit();
  47.             });
  48.         }
  49.     }
  50.     public function onWorkerRunning(): void
  51.     {
  52.         $this->dumpWorkerFile();
  53.     }
  54.     public function onWorkerPing(): void
  55.     {
  56.         $this->dumpWorkerFile();
  57.     }
  58.     public function onWorkerStopped(): void
  59.     {
  60.         $this->filesystem->remove($this->workersPoolPath $this->pid);
  61.     }
  62.     protected function dumpWorkerFile(): void
  63.     {
  64.         $this->filesystem->dumpFile($this->workersPoolPath $this->pidmicrotime(true));
  65.     }
  66. }