<?php declare(strict_types=1);
/**
* @copyright 2021 Crehler Sp. z o. o. <https://crehler.com>
*
* @author Jakub MedyĆski <jme@crehler.com>
* @support Crehler <support@crehler.com>
* @created 13 sty 2021
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Crehler\MojeBambinoEngine\Subscriber;
use Crehler\MojeBambinoEngine\Service\ProductStatusStorefrontService;
use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelEntityLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductStatusSubscriber implements EventSubscriberInterface
{
private ProductStatusStorefrontService $productStatusService;
public function __construct(ProductStatusStorefrontService $productStatusService)
{
$this->productStatusService = $productStatusService;
}
public static function getSubscribedEvents(): array
{
return [
ProductEvents::PRODUCT_LOADED_EVENT => 'onProductLoaded',
SalesChannelEntityLoadedEvent::class => 'onProductLoaded'
];
}
public function onProductLoaded(EntityLoadedEvent $event): void
{
try {
$products = $event->getEntities();
/** @var SalesChannelProductEntity $product */
foreach ($products as $product) {
if ($product instanceof SalesChannelProductEntity && !$product->hasExtension('productStatus')) {
$product->addExtension('productStatus', $this->productStatusService->getProductStatus($product, $event->getContext()));
}
}
} catch (\Throwable $exception) {
dd($exception);
}
}
}