Passed
Pull Request — master (#61)
by
unknown
14:26
created

__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 4
dl 0
loc 10
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitBag\SyliusWishlistPlugin\CommandHandler\Wishlist;
6
7
use BitBag\SyliusWishlistPlugin\Command\Wishlist\RemoveProductVariantFromWishlist;
8
use BitBag\SyliusWishlistPlugin\Exception\ProductVariantNotFoundException;
9
use BitBag\SyliusWishlistPlugin\Exception\WishlistNotFoundException;
10
use BitBag\SyliusWishlistPlugin\Repository\WishlistRepositoryInterface;
11
use Doctrine\Persistence\ObjectManager;
12
use Sylius\Component\Core\Repository\ProductVariantRepositoryInterface;
13
use Sylius\Component\Resource\Repository\RepositoryInterface;
14
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
15
16
final class RemoveProductVariantFromWishlistHandler implements MessageHandlerInterface
17
{
18
    private WishlistRepositoryInterface $wishlistRepository;
19
20
    private ProductVariantRepositoryInterface $productVariantRepository;
21
22
    private RepositoryInterface $wishlistProductRepository;
23
24
    private ObjectManager $wishlistManager;
25
26
    public function __construct(
27
        WishlistRepositoryInterface $wishlistRepository,
28
        ProductVariantRepositoryInterface $productVariantRepository,
29
        RepositoryInterface $wishlistProductRepository,
30
        ObjectManager $wishlistManager
31
    ) {
32
        $this->wishlistRepository = $wishlistRepository;
33
        $this->productVariantRepository = $productVariantRepository;
34
        $this->wishlistProductRepository = $wishlistProductRepository;
35
        $this->wishlistManager = $wishlistManager;
36
    }
37
38
    public function __invoke(RemoveProductVariantFromWishlist $removeProductVariantFromWishlist)
39
    {
40
        $variantId = $removeProductVariantFromWishlist->getProductVariantIdValue();
41
        $token = $removeProductVariantFromWishlist->getWishlistTokenValue();
42
43
        $variant = $this->productVariantRepository->find($variantId);
44
        $wishlistProduct = $this->wishlistProductRepository->findOneBy(['variant' => $variant]);
45
46
        $wishlist = $this->wishlistRepository->findByToken($token);
47
48
        if (null === $variant || null === $wishlistProduct) {
49
            throw new ProductVariantNotFoundException(
50
                sprintf('The Product %s does not exist', $variantId)
51
            );
52
        }
53
54
        if (null === $wishlist) {
55
            throw new WishlistNotFoundException(
56
                sprintf('The Wishlist %s does not exist', $token)
57
            );
58
        }
59
60
        $wishlist->removeProductVariant($variant);
61
        $this->wishlistManager->flush();
62
63
        return $wishlist;
64
    }
65
}
66