Passed
Pull Request — master (#58)
by
unknown
04:56
created

AddProductVariantToWishlistHandler   A

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 9 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
    {
29
        $this->wishlistProductFactory = $wishlistProductFactory;
30
        $this->productVariantRepository = $productVariantRepository;
31
        $this->wishlistManager = $wishlistManager;
32
    }
33
34
    public function __invoke(AddProductVariantToWishlist $addProductVariantToWishlist): WishlistInterface
35
    {
36
        $variantId = $addProductVariantToWishlist->productVariantId;
37
38
        $variant = $this->productVariantRepository->find($variantId);
39
        $wishlist = $addProductVariantToWishlist->getWishlist();
40
41
        if (null === $variant) {
42
            throw new ProductVariantNotFoundException(
43
                sprintf("The ProductVariant %s does not exist", $variantId)
44
            );
45
        }
46
47
        $wishlistProduct = $this->wishlistProductFactory->createForWishlistAndVariant($wishlist, $variant);
48
49
        $wishlist->addWishlistProduct($wishlistProduct);
50
51
        $this->wishlistManager->persist($wishlist);
52
        $this->wishlistManager->flush();
53
54
        return $wishlist;
55
    }
56
}
57