Passed
Pull Request — master (#58)
by
unknown
11:33 queued 52s
created

RemoveProductFromWishlistHandler::__invoke()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 8
c 2
b 0
f 0
nc 4
nop 1
dl 0
loc 16
rs 9.6111
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitBag\SyliusWishlistPlugin\CommandHandler\Wishlist;
6
7
use BitBag\SyliusWishlistPlugin\Command\Wishlist\RemoveProductFromWishlist;
8
use BitBag\SyliusWishlistPlugin\Repository\WishlistRepositoryInterface;
9
use Doctrine\Persistence\ObjectManager;
10
use Sylius\Component\Core\Repository\ProductRepositoryInterface;
11
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
12
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
13
14
final class RemoveProductFromWishlistHandler implements MessageHandlerInterface
15
{
16
    private ProductRepositoryInterface $productRepository;
17
18
    private WishlistRepositoryInterface $wishlistRepository;
19
20
    private ObjectManager $wishlistProductManager;
21
22
    public function __construct(
23
        ProductRepositoryInterface $productRepository,
24
        WishlistRepositoryInterface $wishlistRepository,
25
        ObjectManager $wishlistProductManager
26
    )
27
    {
28
        $this->productRepository = $productRepository;
29
        $this->wishlistRepository = $wishlistRepository;
30
        $this->wishlistProductManager = $wishlistProductManager;
31
    }
32
33
    public function __invoke(RemoveProductFromWishlist $removeProductFromWishlist)
34
    {
35
        $product = $this->productRepository->find($removeProductFromWishlist->getProductId());
36
        $wishlist = $this->wishlistRepository->findByToken($removeProductFromWishlist->getWishlistToken());
37
38
        if (!$product || !$wishlist) {
39
            throw new NotFoundHttpException();
40
        }
41
42
        foreach ($wishlist->getWishlistProducts() as $wishlistProduct) {
43
            if ($product === $wishlistProduct->getProduct()) {
44
                $this->wishlistProductManager->remove($wishlistProduct);
45
            }
46
        }
47
48
        $this->wishlistProductManager->flush();
49
    }
50
}
51