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

AddProductToWishlistHandler::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 11
c 2
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\AddProductToWishlist;
8
use BitBag\SyliusWishlistPlugin\Entity\WishlistInterface;
9
use BitBag\SyliusWishlistPlugin\Exception\ProductNotFoundException;
10
use BitBag\SyliusWishlistPlugin\Exception\WishlistNotFoundException;
11
use BitBag\SyliusWishlistPlugin\Factory\WishlistProductFactoryInterface;
12
use Doctrine\Persistence\ObjectManager;
13
use Sylius\Component\Core\Repository\ProductRepositoryInterface;
14
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
15
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
16
17
class AddProductToWishlistHandler implements MessageHandlerInterface
18
{
19
    private WishlistProductFactoryInterface $wishlistProductFactory;
20
21
    private ProductRepositoryInterface $productRepository;
22
23
    private ObjectManager $wishlistManager;
24
25
    public function __construct(
26
        WishlistProductFactoryInterface $wishlistProductFactory,
27
        ProductRepositoryInterface $productRepository,
28
        ObjectManager $wishlistManager
29
    )
30
    {
31
        $this->wishlistProductFactory = $wishlistProductFactory;
32
        $this->productRepository = $productRepository;
33
        $this->wishlistManager = $wishlistManager;
34
    }
35
36
    public function __invoke(AddProductToWishlist $addProductToWishlist): WishlistInterface
37
    {
38
        $productId = $addProductToWishlist->productId;
39
40
        $product = $this->productRepository->find($productId);
41
        $wishlist = $addProductToWishlist->getWishlist();
42
43
        if (null === $product) {
44
            throw new ProductNotFoundException(
45
                sprintf("The Product %s does not exist", $productId)
46
            );
47
        }
48
49
        $wishlistProduct = $this->wishlistProductFactory->createForWishlistAndProduct($wishlist, $product);
50
51
        $wishlist->addWishlistProduct($wishlistProduct);
52
53
        $this->wishlistManager->persist($wishlist);
54
        $this->wishlistManager->flush();
55
56
        return $wishlist;
57
    }
58
}
59