<?php
/**
* @copyright 2020 Crehler Sp. z o. o. <https://crehler.com>
*
* @author Jakub MedyĆski <jme@crehler.com>
* @support Crehler <support@crehler.com>
* @created 12 maj 2020
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Crehler\SizeTable\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Storefront\Page\Product\ProductPageCriteriaEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductLoaderSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $productRepository;
public function __construct(EntityRepositoryInterface $productRepository)
{
$this->productRepository = $productRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageCriteriaEvent::class => 'onProductCriteria',
ProductPageLoadedEvent::class => 'onProductsLoaded',
];
}
public function onProductCriteria(ProductPageCriteriaEvent $event)
{
try {
$event
->getCriteria()
->addAssociation('sizeTables');
} catch (\Exception $e) {
}
}
public function onProductsLoaded(ProductPageLoadedEvent $event)
{
$product = $event->getPage()->getProduct();
if ($product->getParentId() && ($product->getExtension('sizeTables') === null || $product->getExtension('sizeTables'))) {
$criteria = new Criteria([$product->getParentId()]);
$criteria->addAssociation('sizeTables');
$parent = $this->productRepository->search($criteria, $event->getContext())->first();
$product->addExtension('sizeTables', $parent->getExtension('sizeTables'));
}
}
}