1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Sylius package. |
5
|
|
|
* |
6
|
|
|
* (c) Paweł Jędrzejewski |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Sylius\Bundle\ShopBundle\EventListener; |
15
|
|
|
|
16
|
|
|
use Sylius\Bundle\UserBundle\Event\UserEvent; |
17
|
|
|
use Sylius\Component\Channel\Context\ChannelContextInterface; |
18
|
|
|
use Sylius\Component\Core\Model\ChannelInterface; |
19
|
|
|
use Sylius\Component\Core\Model\OrderInterface; |
20
|
|
|
use Sylius\Component\Core\Repository\OrderRepositoryInterface; |
21
|
|
|
use Sylius\Component\Core\Storage\CartStorageInterface; |
22
|
|
|
|
23
|
|
|
final class UserImpersonatedListener |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* @var CartStorageInterface |
27
|
|
|
*/ |
28
|
|
|
private $cartStorage; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var ChannelContextInterface |
32
|
|
|
*/ |
33
|
|
|
private $channelContext; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @var OrderRepositoryInterface |
37
|
|
|
*/ |
38
|
|
|
private $orderRepository; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param CartStorageInterface $cartStorage |
42
|
|
|
* @param ChannelContextInterface $channelContext |
43
|
|
|
* @param OrderRepositoryInterface $orderRepository |
44
|
|
|
*/ |
45
|
|
|
public function __construct( |
46
|
|
|
CartStorageInterface $cartStorage, |
47
|
|
|
ChannelContextInterface $channelContext, |
48
|
|
|
OrderRepositoryInterface $orderRepository |
49
|
|
|
) { |
50
|
|
|
$this->cartStorage = $cartStorage; |
51
|
|
|
$this->channelContext = $channelContext; |
52
|
|
|
$this->orderRepository = $orderRepository; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param UserEvent $event |
57
|
|
|
*/ |
58
|
|
|
public function onUserImpersonated(UserEvent $event): void |
59
|
|
|
{ |
60
|
|
|
$customer = $event->getUser()->getCustomer(); |
|
|
|
|
61
|
|
|
|
62
|
|
|
/** @var ChannelInterface $channel */ |
63
|
|
|
$channel = $this->channelContext->getChannel(); |
64
|
|
|
|
65
|
|
|
/** @var OrderInterface $cart */ |
66
|
|
|
$cart = $this->orderRepository->findLatestCartByChannelAndCustomer($channel, $customer); |
67
|
|
|
|
68
|
|
|
if ($cart === null) { |
69
|
|
|
$this->cartStorage->removeForChannel($channel); |
70
|
|
|
|
71
|
|
|
return; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$this->cartStorage->setForChannel($channel, $cart); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: