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

ExportWishlistToCsvHandler::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 12
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 BitBag\SyliusWishlistPlugin\Exception\SelectAtLeastOneProductException;
16
use Doctrine\Common\Collections\Collection;
17
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
18
19
final class ExportWishlistToCsvHandler implements MessageHandlerInterface
20
{
21
    private int $itemsProcessed = 0;
22
23
    public function __invoke(ExportWishlistToCsv $exportWishlistToCsv): ?\SplFileObject
24
    {
25
        $wishlistProducts = $exportWishlistToCsv->getWishlistProducts();
26
        $file = $exportWishlistToCsv->getFile();
27
28
        $this->putDataToCsv($wishlistProducts, $file);
29
30
        if (0 === $this->itemsProcessed) {
31
            throw new SelectAtLeastOneProductException();
32
        }
33
34
        return $file;
35
    }
36
37
    private function putDataToCsv(Collection $wishlistProducts, \SplFileObject $file): void
38
    {
39
        /** @var AddWishlistProduct $wishlistProduct */
40
        foreach ($wishlistProducts as $wishlistProduct) {
41
            if (!$wishlistProduct->isSelected()) {
42
                continue;
43
            }
44
            $csvWishlistItem = [
45
                    $wishlistProduct->getCartItem()->getCartItem()->getVariant()->getId(),
46
                    $wishlistProduct->getWishlistProduct()->getProduct()->getId(),
47
                    $wishlistProduct->getCartItem()->getCartItem()->getVariant()->getCode(),
48
                ];
49
            $file->fputcsv($csvWishlistItem);
50
            ++$this->itemsProcessed;
51
        }
52
    }
53
}
54