|
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
|
|
|
/** |
|
35
|
|
|
* @param CustomerRepositoryInterface $customerRepository |
|
36
|
|
|
* @param AddressRepositoryInterface $addressRepository |
|
37
|
|
|
* @param TokenStorageInterface $tokenStorage |
|
38
|
|
|
*/ |
|
39
|
|
|
public function __construct( |
|
40
|
|
|
CustomerRepositoryInterface $customerRepository, |
|
41
|
|
|
AddressRepositoryInterface $addressRepository, |
|
42
|
|
|
TokenStorageInterface $tokenStorage |
|
43
|
|
|
) { |
|
44
|
|
|
$this->customerRepository = $customerRepository; |
|
45
|
|
|
$this->addressRepository = $addressRepository; |
|
46
|
|
|
$this->tokenStorage = $tokenStorage; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
public function handle(SetDefaultAddress $setDefaultAddress): void |
|
50
|
|
|
{ |
|
51
|
|
|
/** @var AddressInterface $address */ |
|
52
|
|
|
$address = $this->addressRepository->find($setDefaultAddress->id()); |
|
53
|
|
|
/** @var ShopUser */ |
|
54
|
|
|
$user = $this->tokenStorage->getToken()->getUser(); |
|
55
|
|
|
|
|
56
|
|
|
$this->assertCurrentUserIsOwner($address, $user); |
|
57
|
|
|
|
|
58
|
|
|
/** @var CustomerInterface $customer */ |
|
59
|
|
|
$customer = $user->getCustomer(); |
|
60
|
|
|
|
|
61
|
|
|
$customer->setDefaultAddress($address); |
|
62
|
|
|
$this->customerRepository->add($customer); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
private function assertCurrentUserIsOwner(AddressInterface $address, ShopUserInterface $user) |
|
66
|
|
|
{ |
|
67
|
|
|
Assert::notNull($address->getCustomer(), 'Address is not associated with any user'); |
|
68
|
|
|
Assert::eq($address->getCustomer()->getId(), $user->getId(), 'Current user is not owner of this address'); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|