<?php
declare(strict_types=1);
namespace App\Controller\Action;
use App\Entity\Product\Product;
use App\Entity\Taxonomy\Taxon;
use App\Repository\Brand\BrandRepository;
use App\Repository\Product\ProductRepository;
use Sylius\Bundle\TaxonomyBundle\Doctrine\ORM\TaxonRepository;
use Sylius\Component\Channel\Context\ChannelContextInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Twig\Environment;
final class DisplayProductByBrandControllerAction
{
private Environment $twig;
private RouterInterface $router;
private ChannelContextInterface $channelContext;
public function __construct(
Environment $twig,
ChannelContextInterface $channelContext,
RouterInterface $router
) {
$this->twig = $twig;
$this->router = $router;
$this->channelContext = $channelContext;
}
public function __invoke(Request $request, BrandRepository $brandRepository, ProductRepository $productRepository, TaxonRepository $taxonRepository) {
$code = $request->get('code');
if (!$code) {
return new RedirectResponse($this->router->generate('app_shop_brand_index'));
}
$brand = $brandRepository->findOneBy(['code' => $code]);
if (!$brand) {
return new RedirectResponse($this->router->generate('app_shop_brand_index'));
}
// trier les produits par catégorie
$taxons = [];
$products = $productRepository->findAllByBrand($brand, $this->channelContext->getChannel());
/** @var Product $product */
foreach ($products as $product) {
/** @var Taxon $taxon */
foreach ($product->getTaxons() as $taxon) {
if ($taxon->getParent()) {
$taxons[$taxon->getId()]['taxon'] = $taxon;
$taxons[$taxon->getId()]['products'][$product->getId()] = $product;
}
}
}
return new Response($this->twig->render('@SyliusShop/Brand/Product/index.html.twig', [
'brand' => $brand,
'taxons' => $taxons
]));
}
}