<?php declare(strict_types=1);
/**
* @copyright 2020 Crehler Sp. z o. o. <https://crehler.com>
*
* @author Jakub MedyĆski <jme@crehler.com>
* @support Crehler <support@crehler.com>
* @created 25 wrz 2020
*
* 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 Crehler\Inspirations\Service\InspirationService;
use Crehler\MojeBambinoEngine\Service\ProductStatusStorefrontService;
use PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean;
use Shopware\Core\Content\Product\Events\ProductIndexerEvent;
use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductListingResultSubscriber implements EventSubscriberInterface
{
private InspirationService $inspirationService;
private ProductStatusStorefrontService $productStatusService;
private bool $skip = false;
public function __construct(InspirationService $inspirationService, ProductStatusStorefrontService $productStatusService)
{
$this->inspirationService = $inspirationService;
$this->productStatusService = $productStatusService;
}
public static function getSubscribedEvents(): array
{
return [
ProductIndexerEvent::class =>['onProductIndexer', 1],
ProductEvents::PRODUCT_LOADED_EVENT => 'handleProductListingResult',
'arrangement_product.loaded' => 'handleProductInspirationLoaded'
];
}
public function onProductIndexer($event)
{
$this->skip = true;
}
public function handleProductInspirationLoaded(EntityLoadedEvent $event): void
{
/** @var InspirationProductEntity $inspirationProduct */
foreach ($event->getEntities() as $inspirationProduct) {
$product = $inspirationProduct->getProduct();
$product->addExtension('productStatus', $this->productStatusService->getProductStatus($product, $event->getContext()));
}
}
public function handleProductListingResult(EntityLoadedEvent $event): void
{
if ($event->getContext()->getScope() === Context::CRUD_API_SCOPE ||
$event->getContext()->getScope() === Context::SYSTEM_SCOPE ||
$this->skip) {
return;
}
$products = $event->getEntities();
$context = $event->getContext();
/** @var SalesChannelProductEntity $product */
foreach ($products as $product) {
/** @var ArrayStruct $foreignKeys */
$foreignKeys = $product->getExtension('foreignKeys');
if (null !== $foreignKeys->offsetGet('inspirationId')) {
$inspiration = $this->inspirationService->getInspirationById(
$foreignKeys->offsetGet('inspirationId'),
$context
);
$product->addExtension('inspiration', $inspiration);
}
}
}
}