Passed
Pull Request — master (#88)
by
unknown
04:45 queued 44s
created

ExportWishlistToCsvHandler::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 14
rs 10
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\CommandHandler\Wishlist;
12
13
use BitBag\SyliusWishlistPlugin\Command\Wishlist\AddWishlistProduct;
14
use BitBag\SyliusWishlistPlugin\Command\Wishlist\ExportWishlistToCsv;
15
use Doctrine\Common\Collections\Collection;
16
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
17
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
18
use Symfony\Contracts\Translation\TranslatorInterface;
19
20
final class ExportWishlistToCsvHandler implements MessageHandlerInterface
21
{
22
    private TranslatorInterface $translator;
23
24
    private FlashBagInterface $flashBag;
25
26
    private int $itemsProcessed = 0;
27
28
    public function __construct(
29
        TranslatorInterface $translator,
30
        FlashBagInterface $flashBag
31
    ) {
32
        $this->translator = $translator;
33
        $this->flashBag = $flashBag;
34
    }
35
36
    public function __invoke(ExportWishlistToCsv $exportWishlistToCsv): ?\SplFileObject
37
    {
38
        $wishlistProducts = $exportWishlistToCsv->getWishlistProducts();
39
        $file = $exportWishlistToCsv->getFile();
40
41
        $this->putDataToCsv($wishlistProducts, $file);
42
43
        if (0 === $this->itemsProcessed) {
44
            $this->flashBag->add('error', $this->translator->trans('bitbag_sylius_wishlist_plugin.ui.select_products'));
45
46
            return null;
47
        }
48
49
        return $file;
50
    }
51
52
    private function putDataToCsv(Collection $wishlistProducts, \SplFileObject $file): void
53
    {
54
        /** @var AddWishlistProduct $wishlistProduct */
55
        foreach ($wishlistProducts as $wishlistProduct) {
56
            if (!$wishlistProduct->isSelected()) {
57
                continue;
58
            }
59
            $csvWishlistItem = [
60
                    $wishlistProduct->getCartItem()->getCartItem()->getVariant()->getId(),
61
                    $wishlistProduct->getWishlistProduct()->getProduct()->getId(),
62
                    $wishlistProduct->getCartItem()->getCartItem()->getVariant()->getCode(),
63
                ];
64
            $file->fputcsv($csvWishlistItem);
65
            ++$this->itemsProcessed;
66
        }
67
    }
68
}
69