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\ShopUser; |
10
|
|
|
use Sylius\Component\Core\Model\ShopUserInterface; |
11
|
|
|
use Sylius\Component\Core\Repository\AddressRepositoryInterface; |
12
|
|
|
use Sylius\Component\Core\Repository\CustomerRepositoryInterface; |
13
|
|
|
use Sylius\ShopApiPlugin\Command\SetDefaultAddress; |
14
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; |
15
|
|
|
use Webmozart\Assert\Assert; |
16
|
|
|
|
17
|
|
|
final class SetDefaultAddressHandler |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var CustomerRepositoryInterface |
21
|
|
|
*/ |
22
|
|
|
private $customerRepository; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var AddressRepositoryInterface |
26
|
|
|
*/ |
27
|
|
|
private $addressRepository; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var TokenStorageInterface |
31
|
|
|
*/ |
32
|
|
|
private $tokenStorage; |
33
|
|
|
|
34
|
|
|
public function __construct( |
35
|
|
|
CustomerRepositoryInterface $customerRepository, |
36
|
|
|
AddressRepositoryInterface $addressRepository, |
37
|
|
|
TokenStorageInterface $tokenStorage |
38
|
|
|
) { |
39
|
|
|
$this->customerRepository = $customerRepository; |
40
|
|
|
$this->addressRepository = $addressRepository; |
41
|
|
|
$this->tokenStorage = $tokenStorage; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function handle(SetDefaultAddress $setDefaultAddress): void |
45
|
|
|
{ |
46
|
|
|
/** @var AddressInterface $address */ |
47
|
|
|
$address = $this->addressRepository->find($setDefaultAddress->id()); |
48
|
|
|
/** @var ShopUser */ |
49
|
|
|
$user = $this->tokenStorage->getToken()->getUser(); |
50
|
|
|
|
51
|
|
|
$this->assertCurrentUserIsOwner($address, $user); |
52
|
|
|
|
53
|
|
|
/** @var CustomerInterface $customer */ |
54
|
|
|
$customer = $user->getCustomer(); |
55
|
|
|
|
56
|
|
|
$customer->setDefaultAddress($address); |
57
|
|
|
$this->customerRepository->add($customer); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user) |
61
|
|
|
{ |
62
|
|
|
Assert::notNull($address->getCustomer(), 'Address is not associated with any user'); |
63
|
|
|
Assert::eq($address->getCustomer()->getId(), $user->getId(), 'Current user is not owner of this address'); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|