<?php declare(strict_types=1);
/**
* @copyright 2020 Crehler Sp. z o. o. <https://crehler.com>
*
* @author Dariusz Indyk <d.indyk@crehler.com>
* @support Crehler <support@crehler.com>
* @created 05.01.2021
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Crehler\Inspirations\Subscriber;
use Crehler\Inspirations\Entity\Inspiration\Aggregate\InspirationProduct\InspirationProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class MediaIntegrationSubscriber implements EventSubscriberInterface
{
private EventDispatcherInterface $eventDispatcher;
public function __construct(EventDispatcherInterface $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
public static function getSubscribedEvents(): array
{
return [
'inspiration_media.loaded' => ['onInspirationMediaLoaded'],
'inspiration_product.loaded' => ['onInspirationProductLoaded'],
'inspiration_media.written' => ['onInspirationMediaWritten']
];
}
public function onInspirationMediaLoaded(EntityLoadedEvent $event): void
{
$mediaDefinition = $event->getDefinition();
$newEvent = new EntityLoadedEvent($mediaDefinition, $event->getEntities(), $event->getContext());
$this->eventDispatcher->dispatch($newEvent, 'crehler.custom_media_wrapped.loaded');
}
public function onInspirationProductLoaded(EntityLoadedEvent $event): void
{
$productMediaDefinition = $event->getDefinition()->getField('product')->getReferenceDefinition()->getField('cover')->getReferenceDefinition();
$mediaDefinition = $productMediaDefinition->getField('media')->getReferenceDefinition();
$productMedias = [];
$medias = [];
/** @var InspirationProductEntity $entity */
foreach ($event->getEntities() as $entity) {
if (!$entity->getProduct() || !$entity->getProduct()->getCover() || !$entity->getProduct()->getCover()->getMedia()) {
continue;
}
$productMedias[] = $entity->getProduct()->getCover();
$medias[] = $entity->getProduct()->getCover()->getMedia();
}
if (!empty($medias)) {
$newEvent = new EntityLoadedEvent($productMediaDefinition, $productMedias, $event->getContext());
$this->eventDispatcher->dispatch($newEvent, 'crehler.custom_media_wrapped.loaded');
$newEvent = new EntityLoadedEvent($mediaDefinition, $medias, $event->getContext());
$this->eventDispatcher->dispatch($newEvent, 'crehler.custom_media.loaded');
}
}
public function onInspirationMediaWritten(EntityWrittenEvent $event): void
{
foreach ($event->getWriteResults() as $writeResult) {
if (isset($writeResult->getPayload()['mediaId'])) {
$this->eventDispatcher->dispatch($event, 'crehler.image_booster.generate_media');
}
}
}
}