<?php
declare(strict_types=1);
namespace App\Component\Wishlist\Controller\Action;
use BitBag\SyliusWishlistPlugin\Entity\WishlistInterface;
use BitBag\SyliusWishlistPlugin\Form\Type\WishlistCollectionType;
use BitBag\SyliusWishlistPlugin\Processor\WishlistCommandProcessorInterface;
use BitBag\SyliusWishlistPlugin\Resolver\WishlistsResolverInterface;
use Doctrine\ORM\EntityManagerInterface;
use Sylius\Component\Order\Context\CartContextInterface;
use Sylius\Component\Order\Context\CartNotFoundException;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;
final class CustomWishlistController
{
public function __construct(
private CartContextInterface $cartContext,
private FormFactoryInterface $formFactory,
private Environment $twigEnvironment,
private WishlistCommandProcessorInterface $wishlistCommandProcessor,
private WishlistsResolverInterface $wishlistsResolver,
private UrlGeneratorInterface $generator,
private EntityManagerInterface $entityManager
) {
}
public function __invoke(Request $request): Response
{
$wishlists = $this->wishlistsResolver->resolveAndCreate();
/** @var WishlistInterface|null $wishlist */
$wishlist = array_shift($wishlists);
if (null === $wishlist) {
$homepageUrl = $this->generator->generate('sylius_shop_homepage');
return new RedirectResponse($homepageUrl);
}
$wishlist->setName('List');
$this->entityManager->persist($wishlist);
$this->entityManager->flush();
try {
$cart = $this->cartContext->getCart();
} catch (CartNotFoundException $exception) {
$cart = null;
}
$commandsArray = $this->wishlistCommandProcessor->createWishlistItemsCollection($wishlist->getWishlistProducts());
$form = $this->formFactory->create(WishlistCollectionType::class, ['items' => $commandsArray], [
'cart' => $cart,
]);
return new Response(
$this->twigEnvironment->render('@BitBagSyliusWishlistPlugin/WishlistDetails/index.html.twig', [
'wishlist' => $wishlist,
'form' => $form->createView(),
])
);
}
}