vendor/shapecode/cron-bundle/src/EventListener/AnnotationJobLoaderListener.php line 39

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Shapecode\Bundle\CronBundle\EventListener;
  4. use Doctrine\Common\Annotations\Reader;
  5. use ReflectionClass;
  6. use Shapecode\Bundle\CronBundle\Annotation\CronJob;
  7. use Shapecode\Bundle\CronBundle\Event\LoadJobsEvent;
  8. use Shapecode\Bundle\CronBundle\Model\CronJobMetadata;
  9. use Symfony\Bundle\FrameworkBundle\Console\Application;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpKernel\KernelInterface;
  12. use function assert;
  13. use function is_string;
  14. final class AnnotationJobLoaderListener implements EventSubscriberInterface
  15. {
  16.     private Application $application;
  17.     private Reader $reader;
  18.     public function __construct(KernelInterface $kernelReader $reader)
  19.     {
  20.         $this->application = new Application($kernel);
  21.         $this->reader      $reader;
  22.     }
  23.     /**
  24.      * @inheritdoc
  25.      */
  26.     public static function getSubscribedEvents(): array
  27.     {
  28.         return [LoadJobsEvent::NAME => 'onLoadJobs'];
  29.     }
  30.     public function onLoadJobs(LoadJobsEvent $event): void
  31.     {
  32.         foreach ($this->application->all() as $command) {
  33.             // Check for an @CronJob annotation
  34.             $reflectionClass = new ReflectionClass($command);
  35.             foreach ($this->reader->getClassAnnotations($reflectionClass) as $annotation) {
  36.                 if (! ($annotation instanceof CronJob)) {
  37.                     continue;
  38.                 }
  39.                 $arguments    $annotation->arguments;
  40.                 $maxInstances $annotation->maxInstances;
  41.                 $schedule     $annotation->value;
  42.                 assert(is_string($schedule));
  43.                 $meta CronJobMetadata::createByCommand($schedule$command$arguments$maxInstances);
  44.                 $event->addJob($meta);
  45.             }
  46.         }
  47.     }
  48. }