Passed
Pull Request — master (#88)
by
unknown
04:13
created

ImportWishlistFromCsvAction::__invoke()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 19
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 32
rs 9.3222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitBag\SyliusWishlistPlugin\Controller\Action;
6
7
use BitBag\SyliusWishlistPlugin\Form\Type\ImportWishlistFromCsvType;
8
use Sylius\Component\Core\Repository\ProductVariantRepositoryInterface;
9
use Symfony\Component\Form\FormFactoryInterface;
10
use Symfony\Component\HttpFoundation\File\UploadedFile;
11
use Symfony\Component\HttpFoundation\RedirectResponse;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\HttpFoundation\Response;
14
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
15
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
16
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
17
use Symfony\Contracts\Translation\TranslatorInterface;
18
use Twig\Environment;
19
20
final class ImportWishlistFromCsvAction
21
{
22
    private FormFactoryInterface $formFactory;
23
24
    private AddProductVariantToWishlistAction $addProductVariantToWishlistAction;
25
26
    private ProductVariantRepositoryInterface $productVariantRepository;
27
28
    private Environment $twigEnvironment;
29
30
    private UrlGeneratorInterface $urlGenerator;
31
32
    private FlashBagInterface $flashBag;
33
34
    private TranslatorInterface $translator;
35
36
    public function __construct(
37
        FormFactoryInterface $formFactory,
38
        Environment $twigEnvironment,
39
        AddProductVariantToWishlistAction $addProductVariantToWishlistAction,
40
        UrlGeneratorInterface $urlGenerator,
41
        FlashBagInterface $flashBag,
42
        ProductVariantRepositoryInterface $productVariantRepository,
43
        TranslatorInterface $translator
44
    ) {
45
        $this->formFactory = $formFactory;
46
        $this->twigEnvironment = $twigEnvironment;
47
        $this->addProductVariantToWishlistAction = $addProductVariantToWishlistAction;
48
        $this->urlGenerator = $urlGenerator;
49
        $this->flashBag = $flashBag;
50
        $this->productVariantRepository = $productVariantRepository;
51
        $this->translator = $translator;
52
    }
53
54
    public function __invoke(Request $request): Response
55
    {
56
        $form = $this->formFactory->create(ImportWishlistFromCsvType::class);
57
58
        $form->handleRequest($request);
59
60
        if ($form->isSubmitted() && $form->isValid()) {
61
            $file = $form->get('wishlist_file')->getData();
62
            if ($this->handleUploadedFile($file, $request)) {
63
                return new RedirectResponse(
64
                    $this->urlGenerator->generate('bitbag_sylius_wishlist_plugin_shop_wishlist_list_products')
65
                );
66
            } else {
67
                $this->flashBag->add(
68
                    'error',
69
                    $this->translator->trans('bitbag_sylius_wishlist_plugin.ui.upload_valid_csv')
70
                );
71
                return new Response(
72
                    $this->twigEnvironment->render('@BitBagSyliusWishlistPlugin/importWishlist.html.twig', [
73
                                'form' => $form->createView(),
74
                        ])
75
                );
76
            }
77
        }
78
79
        foreach ($form->getErrors() as $error) {
80
            $this->flashBag->add('error', $error->getMessage());
0 ignored issues
show
Bug introduced by
The method getMessage() does not exist on Symfony\Component\Form\FormErrorIterator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

80
            $this->flashBag->add('error', $error->/** @scrutinizer ignore-call */ getMessage());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
81
        }
82
83
        return new Response(
84
            $this->twigEnvironment->render('@BitBagSyliusWishlistPlugin/importWishlist.html.twig', [
85
                        'form' => $form->createView(),
86
                ])
87
        );
88
    }
89
90
    private function handleUploadedFile(UploadedFile $file, Request $request): bool
91
    {
92
        if ($this->isValidMimeType($file)) {
93
            $resource = fopen($file->getRealPath(), "r");
94
95
            while ($data = fgetcsv($resource, 1000, ',')) {
96
                if ($this->checkCsvProduct($data)) {
97
                    $request->attributes->set('variantId', $data[0]);
98
                    $this->addProductVariantToWishlistAction->__invoke($request);
99
                }
100
            }
101
            fclose($resource);
102
        } else {
103
            return false;
104
        }
105
        return true;
106
    }
107
108
    private function isValidMimeType(UploadedFile $file): bool
109
    {
110
        return "text/csv" === $file->getClientMimeType();
111
    }
112
113
    private function checkCsvProduct(array $data): bool
114
    {
115
        $variant = $this->productVariantRepository->find($data[0]);
116
117
        if (null === $variant) {
118
            throw new NotFoundHttpException();
119
        }
120
121
        if ($data[1] == $variant->getProduct()->getId() && $data[2] == $variant->getCode()) {
122
            return true;
123
        }
124
        return false;
125
    }
126
}
127