src/Event/FlyOutNavigationSubscriber.php line 44

  1. <?php
  2. namespace App\Event;
  3. use App\Service\Navigation\FlyOutNavigationService;
  4. use Sulu\Bundle\PageBundle\Domain\Event\PagePublishedEvent;
  5. use Sulu\Bundle\PageBundle\Domain\Event\PageUnpublishedEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\Filesystem\Exception\FileNotFoundException;
  8. use Symfony\Component\Filesystem\Filesystem;
  9. class FlyOutNavigationSubscriber implements EventSubscriberInterface
  10. {
  11.     private FlyOutNavigationService $flyOutNavigationService;
  12.     private string $flyOutNavigationDir;
  13.     private string $flyOutNavigationPath;
  14.     public function __construct(FlyOutNavigationService $flyOutNavigationServicestring $projectDir)
  15.     {
  16.         $this->flyOutNavigationService $flyOutNavigationService;
  17.         $this->flyOutNavigationDir     $projectDir '/navigation';
  18.         $this->flyOutNavigationPath    $this->flyOutNavigationDir '/flyOutNavigation.json';
  19.     }
  20.     /**
  21.      * @inheritDoc
  22.      */
  23.     public static function getSubscribedEvents()
  24.     {
  25.         return [
  26.             PagePublishedEvent::class => 'createFlyOutNavigation',
  27.             PageUnpublishedEvent::class => 'createFlyOutNavigation'
  28.         ];
  29.     }
  30.     /**
  31.      * Everytime a page in Backend is published, the fly-out navigation JSON will be updated.
  32.      *
  33.      * @param PagePublishedEvent|PageUnpublishedEvent $event
  34.      * @return void
  35.      */
  36.     public function createFlyOutNavigation(PagePublishedEvent|PageUnpublishedEvent $event): void
  37.     {
  38.         $navigation $this->flyOutNavigationService->getContentFromDB();
  39.         $content json_encode($navigation);
  40.         $filesystem = new Filesystem();
  41.         if (!$filesystem->exists($this->flyOutNavigationDir)) {
  42.             $filesystem->mkdir($this->flyOutNavigationDir);
  43.         }
  44.         file_put_contents($this->flyOutNavigationPath$content);
  45.         if (!file_exists($this->flyOutNavigationPath)) {
  46.             throw new FileNotFoundException('Can not create JSON file for Fly-Out-Navigation!');
  47.         }
  48.     }
  49. }