<?php declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\PageInterface;
use Vich\UploaderBundle\Event\Event;
use Vich\UploaderBundle\Event\Events;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PageAssetsFileSubscriber implements EventSubscriberInterface
{
/**
* @var string
*/
private $projectDir;
public function __construct(KernelInterface $kernel)
{
$this->projectDir = $kernel->getProjectDir();
}
public static function getSubscribedEvents(): array
{
return [
Events::POST_UPLOAD => ['onVichUploaderPostUpload']
];
}
/**
* Unzip the landing pages assets archive and move files to the appropriate places.
*
* @param Event $event
* @return void
* @todo Split the code and make this method part of dedicated service?
*/
public function onVichUploaderPostUpload(Event $event)
{
$entity = $event->getObject();
$mappingName = $event->getMapping()->getMappingName();
if (!$entity instanceof PageInterface || 'page_assets_archive' !== $mappingName) {
return;
}
/** @var PageInterface $page */
$page = $entity;
// Extract the archive files.
$assetsArchiveFile = $page->getAssetsArchiveFile();
$zip = new \ZipArchive;
if (TRUE !== $zip->open($assetsArchiveFile->getRealPath())) {
return;
}
$assetsDirPathName = implode(
DIRECTORY_SEPARATOR,
[
$this->projectDir,
'public',
'uploads',
'assets',
]
);
$assetsDirPathName .= DIRECTORY_SEPARATOR.$page->getFilesystemPath();
$zip->extractTo($assetsDirPathName);
$zip->close();
}
}