<?php
namespace App\EventListener;
use Pimcore\Event\AssetEvents;
use Pimcore\Event\FrontendEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
class S3Listener implements EventSubscriberInterface
{
private $s3BaseUrl;
private $s3TmpUrlPrefix;
private $s3AssetUrlPrefix;
public function __construct()
{
// you have to customize this if you'd like to deliver your assets/thumbnails in your S3 bucket by CloudFront
$this->s3BaseUrl = S3_ASSET_URL_PIMCORE;
$this->s3TmpUrlPrefix = $this->s3BaseUrl . str_replace('s3:/', '', PIMCORE_TEMPORARY_DIRECTORY);
$this->s3AssetUrlPrefix = $this->s3BaseUrl . str_replace('s3:/', '', PIMCORE_ASSET_DIRECTORY);
}
public static function getSubscribedEvents()
{
return [
FrontendEvents::ASSET_IMAGE_THUMBNAIL => 'onFrontendPathThumbnail',
FrontendEvents::ASSET_DOCUMENT_IMAGE_THUMBNAIL => 'onFrontendPathThumbnail',
FrontendEvents::ASSET_VIDEO_IMAGE_THUMBNAIL => 'onFrontendPathThumbnail',
FrontendEvents::ASSET_VIDEO_THUMBNAIL => 'onFrontendPathThumbnail',
FrontendEvents::ASSET_PATH => 'onFrontEndPathAsset',
AssetEvents::IMAGE_THUMBNAIL => 'onAssetThumbnailCreated',
AssetEvents::VIDEO_IMAGE_THUMBNAIL => 'onAssetThumbnailCreated',
AssetEvents::DOCUMENT_IMAGE_THUMBNAIL => 'onAssetThumbnailCreated',
];
}
public function onFrontendPathThumbnail(GenericEvent $event)
{
// rewrite the path for the frontend
$fileSystemPath = $event->getSubject()->getFileSystemPath();
$cacheKey = 'thumb_s3_' . md5($fileSystemPath);
$path = \Pimcore\Cache::load($cacheKey);
if (!$path) {
if (!file_exists($fileSystemPath)) {
// the thumbnail doesn't exist yet, so we need to create it on request -> Thumbnail controller plugin
$path = str_replace(PIMCORE_TEMPORARY_DIRECTORY.'/image-thumbnails', '', $fileSystemPath);
} else {
$path = str_replace(PIMCORE_TEMPORARY_DIRECTORY . '/', $this->s3TmpUrlPrefix . '/', $fileSystemPath);
}
}
$event->setArgument('frontendPath', $path);
}
public function onAssetThumbnailCreated(GenericEvent $event)
{
$thumbnail = $event->getSubject();
$fsPath = $thumbnail->getFileSystemPath();
if ($fsPath && $event->getArgument('generated')) {
$cacheKey = 'thumb_s3_' . md5($fsPath);
\Pimcore\Cache::remove($cacheKey);
}
}
public function onFrontEndPathAsset(GenericEvent $event)
{
$asset = $event->getSubject();
$path = str_replace(PIMCORE_ASSET_DIRECTORY . '/', $this->s3AssetUrlPrefix . '/', $asset->getFrontendPath());
$event->setArgument('frontendPath', $path);
}
}