Passed
Pull Request — master (#85)
by
unknown
05:10 queued 01:29
created

ExportWishlistToPdfAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 12
c 2
b 0
f 0
nc 1
nop 12
dl 0
loc 26
rs 9.8666

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
/*
4
 * This file was created by developers working at BitBag
5
 * Do you need more information about us and what we do? Visit our https://bitbag.io website!
6
 * We are hiring developers from all over the world. Join us and start your new, exciting adventure and become part of us: https://bitbag.io/career
7
*/
8
9
declare(strict_types=1);
10
11
namespace BitBag\SyliusWishlistPlugin\Controller\Action;
12
13
use BitBag\SyliusWishlistPlugin\Command\Wishlist\AddWishlistProduct;
14
use BitBag\SyliusWishlistPlugin\Context\WishlistContextInterface;
15
use BitBag\SyliusWishlistPlugin\Form\Type\WishlistCollectionType;
16
use BitBag\SyliusWishlistPlugin\Model\Factory\VariantPdfModelFactory;
17
use BitBag\SyliusWishlistPlugin\Resolver\VariantImagePathResolverInterface;
18
use Doctrine\ORM\EntityManagerInterface;
19
use Dompdf\Dompdf;
20
use Dompdf\Options;
21
use Sylius\Component\Channel\Context\ChannelContextInterface;
22
use Sylius\Component\Core\Repository\ProductVariantRepositoryInterface;
23
use Sylius\Component\Order\Context\CartContextInterface;
24
use Symfony\Component\Form\FormFactoryInterface;
25
use Symfony\Component\HttpFoundation\RedirectResponse;
26
use Symfony\Component\HttpFoundation\Request;
27
use Symfony\Component\HttpFoundation\Response;
28
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
29
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
30
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
31
use Symfony\Contracts\Translation\TranslatorInterface;
32
use Twig\Environment;
33
34
final class ExportWishlistToPdfAction
35
{
36
    private WishlistContextInterface $wishlistContext;
37
38
    private CartContextInterface $cartContext;
39
40
    private FormFactoryInterface $formFactory;
41
42
    private FlashBagInterface $flashBag;
43
44
    private TranslatorInterface $translator;
45
46
    private ProductVariantRepositoryInterface $productVariantRepository;
47
48
    private UrlGeneratorInterface $urlGenerator;
49
50
    private EntityManagerInterface $wishlistProductManager;
51
52
    private Environment $twigEnvironment;
53
54
    private ChannelContextInterface $channelContext;
55
56
    private VariantImagePathResolverInterface $variantImagePathResolver;
57
    
58
    private VariantPdfModelFactory $variantPdfModelFactory;
59
60
    public function __construct(
61
        WishlistContextInterface          $wishlistContext,
62
        CartContextInterface              $cartContext,
63
        FormFactoryInterface              $formFactory,
64
        FlashBagInterface                 $flashBag,
65
        TranslatorInterface               $translator,
66
        ProductVariantRepositoryInterface $productVariantRepository,
67
        UrlGeneratorInterface             $urlGenerator,
68
        EntityManagerInterface            $wishlistProductManager,
69
        Environment                       $twigEnvironment,
70
        ChannelContextInterface           $channelContext,
71
        VariantImagePathResolverInterface $variantImagePathResolver,
72
        VariantPdfModelFactory            $variantPdfModelFactory
73
    ) {
74
        $this->wishlistContext = $wishlistContext;
75
        $this->cartContext = $cartContext;
76
        $this->formFactory = $formFactory;
77
        $this->flashBag = $flashBag;
78
        $this->translator = $translator;
79
        $this->productVariantRepository = $productVariantRepository;
80
        $this->urlGenerator = $urlGenerator;
81
        $this->wishlistProductManager = $wishlistProductManager;
82
        $this->twigEnvironment = $twigEnvironment;
83
        $this->channelContext = $channelContext;
84
        $this->variantImagePathResolver = $variantImagePathResolver;
85
        $this->variantPdfModelFactory = $variantPdfModelFactory;
86
    }
87
88
    public function __invoke(Request $request): Response
89
    {
90
        $wishlist = $this->wishlistContext->getWishlist($request);
91
        $cart = $this->cartContext->getCart();
92
93
        $commandsArray = [];
94
95
        foreach ($wishlist->getWishlistProducts() as $wishlistProductItem) {
96
            $wishlistProductCommand = new AddWishlistProduct();
97
            $wishlistProductCommand->setWishlistProduct($wishlistProductItem);
98
            $commandsArray[] = $wishlistProductCommand;
99
        }
100
101
        $form = $this->formFactory->create(WishlistCollectionType::class, ['items' => $commandsArray], [
102
            'cart' => $cart,
103
104
        ]);
105
106
        $form->handleRequest($request);
107
108
        if ($form->isSubmitted() && $form->isValid()) {
109
            $wishlistProducts = $form->get("items")->getData();
110
111
            if (!$this->handleCartItems($wishlistProducts, $request)) {
112
                $this->flashBag->add('error', $this->translator->trans('bitbag_sylius_wishlist_plugin.ui.select_products'));
113
            }
114
115
            return new RedirectResponse($this->urlGenerator->generate('bitbag_sylius_wishlist_plugin_shop_wishlist_list_products'));
116
        }
117
118
        foreach ($form->getErrors() as $error) {
119
            $this->flashBag->add('error', $error->getMessage());
120
        }
121
122
        return new Response(
123
            $this->twigEnvironment->render('@BitBagSyliusWishlistPlugin/WishlistDetails/index.html.twig', [
124
                'wishlist' => $wishlist,
125
                'form' => $form->createView(),
126
            ])
127
        );
128
    }
129
130
    private function handleCartItems(array $wishlistProducts, Request $request): bool
131
    {
132
        $result = false;
133
        $selectedProducts = [];
134
        /** @var AddWishlistProduct $wishlistProduct */
135
        foreach ($wishlistProducts as $wishlistProduct) {
136
            if ($wishlistProduct->isSelected()) {
137
                $result = true;
138
                $variant = $this->productVariantRepository->find($wishlistProduct->getWishlistProduct()->getVariant());
139
140
                if (null === $variant) {
141
                    throw new NotFoundHttpException();
142
                }
143
144
                $cartItem = $wishlistProduct->getCartItem()->getCartItem();
145
                $quantity = $cartItem->getQuantity();
146
                $baseUrl = $request->getSchemeAndHttpHost();
147
                $urlToImage = $this->variantImagePathResolver->resolve($variant, $baseUrl);
148
                $actualVariant = $cartItem->getVariant()->getCode();
149
150
                $selectedProducts[] = $this->variantPdfModelFactory->createWithVariantAndImagePath($variant,$urlToImage,$quantity,$actualVariant);
151
            }
152
        }
153
        if (true === $result) {
154
            $this->exportToPdf($selectedProducts);
155
        }
156
157
        return $result;
158
    }
159
160
    public function exportToPdf(array $selectedProducts): void
161
    {
162
        $pdfOptions = new Options();
163
        $pdfOptions->set('isRemoteEnabled', true);
164
        $pdfOptions->set('defaultFont', 'Arial');
165
        $dompdf = new Dompdf($pdfOptions);
166
        $html = $this->twigEnvironment->render('@BitBagSyliusWishlistPlugin/_wishlist_pdf.html.twig', [
167
            'title' => "My wishlist products",
168
            'date' => date("d.m.Y"),
169
            'products' => $selectedProducts
170
        ]);
171
172
        $dompdf->loadHtml($html);
173
        $dompdf->setPaper('A4', 'portrait');
174
        $dompdf->render();
175
        $dompdf->stream('wishlist.pdf', ["Attachment" => true]);
176
    }
177
}
178