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

AddProductVariantToWishlistHandler::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 11
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 21
rs 9.9
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