src/EventSubscriber/PageAssetsFileSubscriber.php line 37

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace App\EventSubscriber;
  3. use App\Entity\PageInterface;
  4. use Vich\UploaderBundle\Event\Event;
  5. use Vich\UploaderBundle\Event\Events;
  6. use Symfony\Component\HttpKernel\KernelInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class PageAssetsFileSubscriber implements EventSubscriberInterface
  9. {
  10.     /**
  11.      * @var string
  12.      */
  13.     private $projectDir;
  14.     public function __construct(KernelInterface $kernel)
  15.     {
  16.         $this->projectDir $kernel->getProjectDir();
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             Events::POST_UPLOAD => ['onVichUploaderPostUpload']
  22.         ];
  23.     }
  24.     /**
  25.      * Unzip the landing pages assets archive and move files to the appropriate places.
  26.      *
  27.      * @param Event $event
  28.      * @return void
  29.      * @todo Split the code and make this method part of dedicated service?
  30.      */
  31.     public function onVichUploaderPostUpload(Event $event)
  32.     {
  33.         $entity $event->getObject();
  34.         $mappingName $event->getMapping()->getMappingName();
  35.         if (!$entity instanceof PageInterface || 'page_assets_archive' !== $mappingName) {
  36.             return;
  37.         }
  38.         /** @var PageInterface $page */
  39.         $page $entity;
  40.         // Extract the archive files.
  41.         $assetsArchiveFile $page->getAssetsArchiveFile();
  42.         $zip = new \ZipArchive;
  43.         if (TRUE !== $zip->open($assetsArchiveFile->getRealPath())) {
  44.             return;
  45.         }
  46.         $assetsDirPathName implode(
  47.             DIRECTORY_SEPARATOR,
  48.             [
  49.                 $this->projectDir,
  50.                 'public',
  51.                 'uploads',
  52.                 'assets',
  53.             ]
  54.         );
  55.         $assetsDirPathName .= DIRECTORY_SEPARATOR.$page->getFilesystemPath();
  56.         $zip->extractTo($assetsDirPathName);
  57.         $zip->close();
  58.     }
  59. }