<?php
namespace Appflix\Studygood\Storefront\Subscriber;
use Shopware\Core\Content\Media\MediaEntity;
use Shopware\Core\Content\Media\MediaEvents;
use Shopware\Core\Content\Media\Pathname\UrlGeneratorInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use League\Flysystem\FilesystemInterface;
class MediaLoadedSubscriber implements EventSubscriberInterface
{
private FilesystemInterface $filesystemPublic;
private FilesystemInterface $filesystemPrivate;
private UrlGeneratorInterface $urlGenerator;
public function __construct(
FilesystemInterface $fileSystemPublic,
FilesystemInterface $fileSystemPrivate,
UrlGeneratorInterface $urlGenerator
) {
$this->filesystemPublic = $fileSystemPublic;
$this->filesystemPrivate = $fileSystemPrivate;
$this->urlGenerator = $urlGenerator;
}
public static function getSubscribedEvents(): array
{
return [
MediaEvents::MEDIA_LOADED_EVENT => 'transformSvgMedia',
];
}
public function transformSvgMedia(EntityLoadedEvent $event): void
{
//return;
/** @var MediaEntity $media */
foreach ($event->getEntities() as $media) {
if (!$media->hasFile() || $media->isPrivate()) {
continue;
}
if (strpos($media->getMimeType(), 'image/svg') !== false) {
$this->enrichSvgContents($media);
}
}
}
private function enrichSvgContents(MediaEntity $media): void
{
$filePath = $this->urlGenerator->getRelativeMediaUrl($media);
try {
/** @var string $file */
$file = $this->getFileSystem($media)->read($filePath);
$media->assign(['svg' => $file]);
} catch (\Exception $exception) {
}
}
private function getFileSystem(MediaEntity $media): FilesystemInterface
{
if ($media->isPrivate()) {
return $this->filesystemPrivate;
}
return $this->filesystemPublic;
}
}