AddProductVariantToWishlistHandler   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 18
c 2
b 0
f 0
dl 0
loc 40
rs 10
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A __invoke() 0 22 2
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\AddProductVariantToWishlist;
14
use BitBag\SyliusWishlistPlugin\Entity\WishlistInterface;
15
use BitBag\SyliusWishlistPlugin\Exception\ProductVariantNotFoundException;
16
use BitBag\SyliusWishlistPlugin\Factory\WishlistProductFactoryInterface;
17
use Doctrine\Persistence\ObjectManager;
18
use Sylius\Component\Core\Model\ProductVariantInterface;
19
use Sylius\Component\Core\Repository\ProductVariantRepositoryInterface;
20
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
21
22
final class AddProductVariantToWishlistHandler implements MessageHandlerInterface
23
{
24
    private WishlistProductFactoryInterface $wishlistProductFactory;
25
26
    private ProductVariantRepositoryInterface $productVariantRepository;
27
28
    private ObjectManager $wishlistManager;
29
30
    public function __construct(
31
        WishlistProductFactoryInterface $wishlistProductFactory,
32
        ProductVariantRepositoryInterface $productVariantRepository,
33
        ObjectManager $wishlistManager
34
    ) {
35
        $this->wishlistProductFactory = $wishlistProductFactory;
36
        $this->productVariantRepository = $productVariantRepository;
37
        $this->wishlistManager = $wishlistManager;
38
    }
39
40
    public function __invoke(AddProductVariantToWishlist $addProductVariantToWishlist): WishlistInterface
41
    {
42
        $variantId = $addProductVariantToWishlist->productVariantId;
43
44
        /** @var ?ProductVariantInterface $variant */
45
        $variant = $this->productVariantRepository->find($variantId);
46
        $wishlist = $addProductVariantToWishlist->getWishlist();
47
48
        if (null === $variant) {
49
            throw new ProductVariantNotFoundException(
50
                sprintf('The ProductVariant %s does not exist', $variantId)
51
            );
52
        }
53
54
        $wishlistProduct = $this->wishlistProductFactory->createForWishlistAndVariant($wishlist, $variant);
55
56
        $wishlist->addWishlistProduct($wishlistProduct);
57
58
        $this->wishlistManager->persist($wishlist);
59
        $this->wishlistManager->flush();
60
61
        return $wishlist;
62
    }
63
}
64