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

RemoveAddressHandler   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 1
dl 0
loc 43
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A handle() 0 10 1
A assertOrderWithAddressNotExists() 0 8 1
A assertCurrentUserIsOwner() 0 4 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 Webmozart\Assert\Assert;
14
15
class RemoveAddressHandler
16
{
17
    /**
18
     * @var AddressRepositoryInterface
19
     */
20
    private $addressRepository;
21
22
    /**
23
     * @var OrderRepositoryInterface
24
     */
25
    private $orderRepository;
26
27
    public function __construct(AddressRepositoryInterface $addressRepository, OrderRepositoryInterface $orderRepository)
28
    {
29
        $this->addressRepository = $addressRepository;
30
        $this->orderRepository = $orderRepository;
31
    }
32
33
    public function handle(RemoveAddress $removeAddress)
34
    {
35
        /** @var AddressInterface $address */
36
        $address = $this->addressRepository->findOneBy(['id' => $removeAddress->id]);
37
38
        $this->assertCurrentUserIsOwner($address, $removeAddress->user);
39
        $this->assertOrderWithAddressNotExists($address);
40
41
        $this->addressRepository->remove($address);
42
    }
43
44
    private function assertOrderWithAddressNotExists($address)
45
    {
46
        /** @var OrderInterface $orderShippingAddress */
47
        $orderShippingAddress = $this->orderRepository->findBy(['billingAddress' => $address]);
48
        /** @var OrderInterface $orderBillingAddress */
49
        $orderBillingAddress = $this->orderRepository->findBy(['shippingAddress' => $address]);
50
        Assert::allIsEmpty([$orderShippingAddress, $orderBillingAddress], 'Cant delete address because it is associated with one or more orders');
51
    }
52
53
    private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user)
54
    {
55
        Assert::eq($address->getCustomer()->getId(), $user->getId(), 'User is not owner of this address');
56
    }
57
}
58