1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace FH\Bundle\UserAgentBundle\EventListener; |
5
|
|
|
|
6
|
|
|
use FH\Bundle\UserAgentBundle\Entity\UserAgent; |
7
|
|
|
use FH\Bundle\UserAgentBundle\Repository\UserAgentRepositoryInterface; |
8
|
|
|
use FH\Bundle\UserAgentBundle\Request\Request; |
9
|
|
|
use FH\Bundle\UserAgentBundle\Response\Response; |
10
|
|
|
use Symfony\Component\HttpKernel\Event\FilterResponseEvent; |
11
|
|
|
use Symfony\Component\HttpKernel\HttpKernelInterface; |
12
|
|
|
|
13
|
|
|
use function is_a; |
14
|
|
|
use function sprintf; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @author Evert Harmeling <[email protected]> |
18
|
|
|
*/ |
19
|
|
|
final class ResponseListener |
20
|
|
|
{ |
21
|
|
|
public const CRITERIA_HOST = 'host'; |
22
|
|
|
|
23
|
|
|
private $userAgentRepository; |
24
|
|
|
private $criteria; |
25
|
|
|
|
26
|
|
|
public function __construct(UserAgentRepositoryInterface $userAgentRepository, array $criteria = []) |
27
|
|
|
{ |
28
|
|
|
$this->userAgentRepository = $userAgentRepository; |
29
|
|
|
$this->criteria = $criteria; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function __invoke(FilterResponseEvent $event): void |
33
|
|
|
{ |
34
|
|
|
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) { |
35
|
|
|
return; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
if ($this->hasCriteria(self::CRITERIA_HOST)) { |
39
|
|
|
if ($event->getRequest()->getHost() !== $this->getCriteria(self::CRITERIA_HOST)) { |
40
|
|
|
return; |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$userAgentHeader = $event->getRequest()->headers->get(Request::HEADER_USER_AGENT); |
45
|
|
|
|
46
|
|
|
if (!is_string($userAgentHeader)) { |
|
|
|
|
47
|
|
|
return; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$userAgent = $this->userAgentRepository->find($userAgentHeader); |
51
|
|
|
|
52
|
|
|
if (is_a($userAgent, UserAgent::class)) { |
53
|
|
|
$event->getResponse()->headers->set( |
54
|
|
|
Response::HEADER_USER_AGENT_STATUS, $userAgent->getAction()->getValue() |
55
|
|
|
); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function onKernelResponse(FilterResponseEvent $event): void |
60
|
|
|
{ |
61
|
|
|
$this->__invoke($event); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
private function hasCriteria(string $value): bool |
65
|
|
|
{ |
66
|
|
|
return isset($this->criteria[$value]); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return mixed |
71
|
|
|
*/ |
72
|
|
|
private function getCriteria(string $value) |
73
|
|
|
{ |
74
|
|
|
if (!$this->hasCriteria($value)) { |
75
|
|
|
throw new \RuntimeException(sprintf("The criteria '%s' is not set, please configure it", $value)); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $this->criteria[$value]; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|