<?php
declare(strict_types=1);
namespace BitBag\OpenMarketplace\Component\Core\Shop\Controller\Country;
use BitBag\OpenMarketplace\Component\Elasticsearch\Finder\CountryProductsFinderInterface;
use BitBag\OpenMarketplace\Component\Elasticsearch\Form\Resolver\ListProductsFacetsResolverInterface;
use BitBag\OpenMarketplace\Component\Elasticsearch\Form\Type\ListProductsType;
use BitBag\OpenMarketplace\Component\Elasticsearch\Provider\RedirectResponseProviderInterface;
use Sylius\Component\Addressing\Model\CountryInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Twig\Environment;
final class IndexAction
{
public function __construct(
private RepositoryInterface $countryRepository,
private CountryProductsFinderInterface $countryProductsFinder,
private Environment $twig,
private FormFactoryInterface $formFactory,
private ListProductsFacetsResolverInterface $facetsResolver,
private RedirectResponseProviderInterface $redirectResponseProvider,
) {
}
public function __invoke(Request $request): Response
{
$countryCode = $request->get('code');
$redirectResponse = $this->redirectResponseProvider->provide($request, [
'code' => $countryCode,
]);
if (null !== $redirectResponse) {
return $redirectResponse;
}
$country = $this->countryRepository->findOneBy(['code' => $countryCode]);
if (!$country instanceof CountryInterface) {
throw new NotFoundHttpException(sprintf('Country with code "%s" was not found.', $countryCode));
}
$data = [
'country_code' => $country->getCode(),
'name' => null,
];
$form = $this->formFactory->create(ListProductsType::class, $data, [
'facets_resolver' => $this->facetsResolver,
]);
$form->handleRequest($request);
$data = array_merge(
$data,
$form->getData(),
$request->query->all(),
);
$products = $this->countryProductsFinder->find($data);
return new Response($this->twig->render('Context/Shop/Country/index.html.twig', [
'form' => $form->createView(),
'products' => $products,
'country' => $country,
]));
}
}