<?php
declare(strict_types=1);
namespace SchilderSysteme\Subscriber;
use SchilderSysteme\Traits\ThemeTrait;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
use ThemeTrait;
private $productRepository;
private $themeRepository;
public function __construct(
EntityRepositoryInterface $productRepository,
EntityRepositoryInterface $themeRepository
)
{
$this->productRepository = $productRepository;
$this->themeRepository = $themeRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'loadVariants'
];
}
/**
* Add all variants info for displayed products
*
* @param ProductPageLoadedEvent $event
*/
public function loadVariants(ProductPageLoadedEvent $event)
{
if(!$this->isCorrectTheme($event->getContext(), $event->getSalesChannelContext(), $this->themeRepository)){
return;
}
$product = $event->getPage()->getProduct();
$context = $event->getContext();
if(!$product->getParentId()){
return;
}
$variants = $this->getVariants($product->getParentId(), $context);
$customFields = $product->getCustomFields();
$customFields['variants'] = $variants;
$product->setCustomFields($customFields);
}
/**
* Get variants with properties
*
* @param $parentId
* @param Context $context
* @return array
*/
private function getVariants($parentId, Context $context)
{
$parentFilter = new EqualsFilter('parentId', $parentId);
$criteria = (new Criteria())
->addFilter($parentFilter)
->addAssociation('options.group')
->addAssociation('prices');
return $this->productRepository->search($criteria, $context)->getElements();
}
}