Failed Conditions
Pull Request — master (#229)
by
unknown
06:06
created

assertOrderWithAddressNotExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sylius\ShopApiPlugin\Handler;
6
7
use Sylius\Component\Core\Model\AddressInterface;
8
use Sylius\Component\Core\Model\OrderInterface;
9
use Sylius\Component\Core\Model\ShopUserInterface;
10
use Sylius\Component\Core\Repository\AddressRepositoryInterface;
11
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
12
use Sylius\ShopApiPlugin\Command\RemoveAddress;
13
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
14
use Webmozart\Assert\Assert;
15
16
final class RemoveAddressHandler
17
{
18
    /**
19
     * @var AddressRepositoryInterface
20
     */
21
    private $addressRepository;
22
23
    /**
24
     * @var OrderRepositoryInterface
25
     */
26
    private $orderRepository;
27
28
    /**
29
     * @var TokenStorageInterface
30
     */
31
    private $tokenStorage;
32
33
    public function __construct(AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository, TokenStorageInterface $tokenStorage)
34
    {
35
        $this->addressRepository = $addressRepository;
36
        $this->orderRepository = $orderRepository;
37
        $this->tokenStorage = $tokenStorage;
38
    }
39
40
    public function handle(RemoveAddress $removeAddress)
41
    {
42
        /** @var ShopUserInterface $user */
43
        $user = $this->tokenStorage->getToken()->getUser();
44
45
        /** @var AddressInterface $address */
46
        $address = $this->addressRepository->findOneBy(['id' => $removeAddress->id]);
47
48
        $this->assertCurrentUserIsOwner($address, $user);
49
        $this->assertOrderWithAddressNotExists($address);
50
51
        $this->addressRepository->remove($address);
52
    }
53
54
    private function assertOrderWithAddressNotExists($address)
55
    {
56
        /** @var OrderInterface $orderShippingAddress */
57
        $orderShippingAddress = $this->orderRepository->findBy(['billingAddress' => $address]);
58
        /** @var OrderInterface $orderBillingAddress */
59
        $orderBillingAddress = $this->orderRepository->findBy(['shippingAddress' => $address]);
60
        Assert::allIsEmpty([$orderShippingAddress, $orderBillingAddress], 'Cant delete address because it is associated with one or more orders');
61
    }
62
63
    private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user)
64
    {
65
        Assert::eq($address->getCustomer()->getId(), $user->getId(), 'User is not owner of this address');
66
    }
67
}
68