|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PTS\SyliusReferralPlugin\Listener; |
|
4
|
|
|
|
|
5
|
|
|
use PTS\SyliusReferralPlugin\Entity\Customer; |
|
6
|
|
|
use PTS\SyliusReferralPlugin\Service\ReferralManager; |
|
7
|
|
|
use Sylius\Bundle\CoreBundle\Doctrine\ORM\CustomerRepository; |
|
8
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseEvent; |
|
9
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpException; |
|
10
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; |
|
11
|
|
|
|
|
12
|
|
|
class ReferralLinkListener |
|
13
|
|
|
{ |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* @var ReferralManager |
|
17
|
|
|
*/ |
|
18
|
|
|
private $referralManager; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var TokenStorage |
|
22
|
|
|
*/ |
|
23
|
|
|
private $tokenStorage; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var CustomerRepository |
|
27
|
|
|
*/ |
|
28
|
|
|
private $customerRepository; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* ReferralLinkListener constructor. |
|
32
|
|
|
* @param ReferralManager $referralManager |
|
33
|
|
|
* @param TokenStorage $tokenStorage |
|
34
|
|
|
* @param CustomerRepository $customerRepository |
|
35
|
|
|
*/ |
|
36
|
|
|
public function __construct( |
|
37
|
|
|
ReferralManager $referralManager, |
|
38
|
|
|
TokenStorage $tokenStorage, |
|
39
|
|
|
CustomerRepository $customerRepository |
|
40
|
|
|
) { |
|
41
|
|
|
$this->referralManager = $referralManager; |
|
42
|
|
|
$this->tokenStorage = $tokenStorage; |
|
43
|
|
|
$this->customerRepository = $customerRepository; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
|
|
47
|
|
|
public function onRequest(GetResponseEvent $event) |
|
48
|
|
|
{ |
|
49
|
|
|
$this->checkUser(); |
|
50
|
|
|
$this->referralManager->checkReferralValidity(); |
|
51
|
|
|
$token = $this->tokenStorage->getToken(); |
|
52
|
|
|
if (isset($token) && |
|
53
|
|
|
$token->getUser() === 'anon.' |
|
54
|
|
|
) { |
|
55
|
|
|
if ($event->getRequest()->query->has('refId')) { |
|
56
|
|
|
$id = $event->getRequest()->query->get('refId'); |
|
57
|
|
|
$this->checkIdValidity($id); |
|
58
|
|
|
$this->referralManager->setReferral($id); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
private function checkUser() |
|
64
|
|
|
{ |
|
65
|
|
|
$token = $this->tokenStorage->getToken(); |
|
66
|
|
|
if (isset($token) && |
|
67
|
|
|
$token->getUser() !== 'anon.' |
|
68
|
|
|
) { |
|
69
|
|
|
$this->referralManager->removeReferral(); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
private function checkIdValidity($id) |
|
74
|
|
|
{ |
|
75
|
|
|
/** @var Customer $idOwner */ |
|
76
|
|
|
$idOwner = $this->customerRepository->findOneBy(['id' => $id]); |
|
77
|
|
|
if (!$idOwner) { |
|
|
|
|
|
|
78
|
|
|
throw new HttpException(400, 'Invalid referral'); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|