<?php declare(strict_types=1);
namespace Nds\RecipeManager\Subscriber;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
class RecipeSubscriber implements EventSubscriberInterface
{
private $recipeRepository;
public function __construct(
EntityRepositoryInterface $recipeRepository
) {
$this->recipeRepository = $recipeRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductPageLoaded',
];
}
public function onProductPageLoaded(ProductPageLoadedEvent $event): void
{
$context = $event->getSalesChannelContext()->getContext();
$productId = $event->getPage()->getProduct()->getId();
$recipeExtension['recipeExtension'] = [];
$criteria = new Criteria();
$criteria->addAssociation('ingredients');
$criteria->addFilter(new EqualsFilter('ingredients.productId', $productId));
$recipes = $this->recipeRepository->search($criteria, $context);
if ($recipes->getElements()) {
$recipeExtension['recipeExtension'] = array_values($recipes->getElements());
$event->getPage()->setExtensions($recipeExtension);
}
}
}