Passed
Pull Request — master (#61)
by
unknown
05:43
created

CreateWishlistHandler   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 37
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A __invoke() 0 15 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitBag\SyliusWishlistPlugin\CommandHandler\Wishlist;
6
7
use BitBag\SyliusWishlistPlugin\Command\Wishlist\CreateWishlist;
8
use BitBag\SyliusWishlistPlugin\Entity\WishlistInterface;
9
use BitBag\SyliusWishlistPlugin\Factory\WishlistFactoryInterface;
10
use BitBag\SyliusWishlistPlugin\Resolver\ShopUserWishlistResolverInterface;
11
use Doctrine\Persistence\ObjectManager;
12
use Sylius\Component\Core\Model\ShopUserInterface;
13
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
14
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
15
16
final class CreateWishlistHandler implements MessageHandlerInterface
17
{
18
    private TokenStorageInterface $tokenStorage;
19
20
    private WishlistFactoryInterface $wishlistFactory;
21
22
    private ShopUserWishlistResolverInterface $shopUserWishlistResolver;
23
24
    private ObjectManager $wishlistManager;
25
26
    public function __construct(
27
        TokenStorageInterface $tokenStorage,
28
        WishlistFactoryInterface $wishlistFactory,
29
        ShopUserWishlistResolverInterface $shopUserWishlistResolver,
30
        ObjectManager $wishlistManager
31
    ) {
32
        $this->tokenStorage = $tokenStorage;
33
        $this->wishlistFactory = $wishlistFactory;
34
        $this->shopUserWishlistResolver = $shopUserWishlistResolver;
35
        $this->wishlistManager = $wishlistManager;
36
    }
37
38
    public function __invoke(CreateWishlist $createWishlist): WishlistInterface
39
    {
40
        $token = $this->tokenStorage->getToken();
41
        $user = $token ? $token->getUser() : null;
42
43
        if ($user instanceof ShopUserInterface) {
44
            $wishlist = $this->shopUserWishlistResolver->resolve($user);
45
        } else {
46
            $wishlist = $this->wishlistFactory->createNew();
47
        }
48
49
        $this->wishlistManager->persist($wishlist);
50
        $this->wishlistManager->flush();
51
52
        return $wishlist;
53
    }
54
}
55