Completed
Push — master ( 4c9fb6...4ad644 )
by
unknown
25s queued 11s
created

AddProductVariantToWishlistHandler   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A __invoke() 0 21 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitBag\SyliusWishlistPlugin\CommandHandler\Wishlist;
6
7
use BitBag\SyliusWishlistPlugin\Command\Wishlist\AddProductVariantToWishlist;
8
use BitBag\SyliusWishlistPlugin\Entity\WishlistInterface;
9
use BitBag\SyliusWishlistPlugin\Exception\ProductVariantNotFoundException;
10
use BitBag\SyliusWishlistPlugin\Factory\WishlistProductFactoryInterface;
11
use Doctrine\Persistence\ObjectManager;
12
use Sylius\Component\Core\Repository\ProductVariantRepositoryInterface;
13
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
14
15
final class AddProductVariantToWishlistHandler implements MessageHandlerInterface
16
{
17
    private WishlistProductFactoryInterface $wishlistProductFactory;
18
19
    private ProductVariantRepositoryInterface $productVariantRepository;
20
21
    private ObjectManager $wishlistManager;
22
23
    public function __construct(
24
        WishlistProductFactoryInterface $wishlistProductFactory,
25
        ProductVariantRepositoryInterface $productVariantRepository,
26
        ObjectManager $wishlistManager
27
    ) {
28
        $this->wishlistProductFactory = $wishlistProductFactory;
29
        $this->productVariantRepository = $productVariantRepository;
30
        $this->wishlistManager = $wishlistManager;
31
    }
32
33
    public function __invoke(AddProductVariantToWishlist $addProductVariantToWishlist): WishlistInterface
34
    {
35
        $variantId = $addProductVariantToWishlist->productVariantId;
36
37
        $variant = $this->productVariantRepository->find($variantId);
38
        $wishlist = $addProductVariantToWishlist->getWishlist();
39
40
        if (null === $variant) {
41
            throw new ProductVariantNotFoundException(
42
                sprintf('The ProductVariant %s does not exist', $variantId)
43
            );
44
        }
45
46
        $wishlistProduct = $this->wishlistProductFactory->createForWishlistAndVariant($wishlist, $variant);
47
48
        $wishlist->addWishlistProduct($wishlistProduct);
49
50
        $this->wishlistManager->persist($wishlist);
51
        $this->wishlistManager->flush();
52
53
        return $wishlist;
54
    }
55
}
56