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

AddProductToWishlistHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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