Completed
Pull Request — master (#229)
by
unknown
02:44
created

SetDefaultAddressHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 3
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\CustomerInterface;
9
use Sylius\Component\Core\Model\ShopUserInterface;
10
use Sylius\Component\Core\Repository\AddressRepositoryInterface;
11
use Sylius\Component\Core\Repository\CustomerRepositoryInterface;
12
use Sylius\Component\Resource\Repository\RepositoryInterface;
13
use Sylius\ShopApiPlugin\Command\SetDefaultAddress;
14
use Webmozart\Assert\Assert;
15
16
final class SetDefaultAddressHandler
17
{
18
    /**
19
     * @var CustomerRepositoryInterface
20
     */
21
    private $customerRepository;
22
23
    /**
24
     * @var AddressRepositoryInterface
25
     */
26
    private $addressRepository;
27
28
    /**
29
     * @var RepositoryInterface
30
     */
31
    private $shopUserRepository;
32
33
    /**
34
     * @param CustomerRepositoryInterface $customerRepository
35
     * @param AddressRepositoryInterface $addressRepository
36
     * @param RepositoryInterface $shopUserRepository
37
     */
38
    public function __construct(
39
        CustomerRepositoryInterface $customerRepository,
40
        AddressRepositoryInterface $addressRepository,
41
        RepositoryInterface $shopUserRepository
42
    ) {
43
        $this->customerRepository = $customerRepository;
44
        $this->addressRepository = $addressRepository;
45
        $this->shopUserRepository = $shopUserRepository;
46
    }
47
48
    public function handle(SetDefaultAddress $setDefaultAddress): void
49
    {
50
        /** @var AddressInterface $address */
51
        $address = $this->addressRepository->find($setDefaultAddress->id());
52
        /** @var ShopUserInterface $shopUser */
53
        $shopUser = $this->shopUserRepository->findOneBy(['username' => $setDefaultAddress->userEmail()]);
54
55
        $this->assertCurrentUserIsOwner($address, $shopUser);
56
57
        /** @var CustomerInterface $customer */
58
        $customer = $shopUser->getCustomer();
59
60
        $customer->setDefaultAddress($address);
61
        $this->customerRepository->add($customer);
62
    }
63
64
    private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user)
65
    {
66
        Assert::notNull($address->getCustomer(), 'Address is not associated with any user.');
67
        Assert::eq($address->getCustomer()->getId(), $user->getId(), 'Current user is not owner of this address.');
68
    }
69
}
70