|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Facile\ZFLinkHeadersModule\Listener; |
|
6
|
|
|
|
|
7
|
|
|
use Facile\ZFLinkHeadersModule\OptionsInterface; |
|
8
|
|
|
use Zend\Http\PhpEnvironment\Response; |
|
9
|
|
|
use Zend\Mvc\MvcEvent; |
|
10
|
|
|
use Zend\View\Helper\HeadLink; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Class LinkHandler |
|
14
|
|
|
*/ |
|
15
|
|
|
final class LinkHandler extends AbstractLinkHandler |
|
16
|
|
|
{ |
|
17
|
|
|
const ALLOWED_RELS = [ |
|
18
|
|
|
OptionsInterface::MODE_PRELOAD, |
|
19
|
|
|
OptionsInterface::MODE_PREFETCH, |
|
20
|
|
|
OptionsInterface::MODE_DNS_PREFETCH, |
|
21
|
|
|
OptionsInterface::MODE_PRECONNECT, |
|
22
|
|
|
OptionsInterface::MODE_PRERENDER, |
|
23
|
|
|
]; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var HeadLink |
|
27
|
|
|
*/ |
|
28
|
|
|
private $headLink; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @var OptionsInterface |
|
32
|
|
|
*/ |
|
33
|
|
|
private $options; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* LinkHandler constructor. |
|
37
|
|
|
* |
|
38
|
|
|
* @param HeadLink $headLink |
|
39
|
|
|
* @param OptionsInterface $options |
|
40
|
|
|
*/ |
|
41
|
9 |
|
public function __construct(HeadLink $headLink, OptionsInterface $options) |
|
42
|
|
|
{ |
|
43
|
9 |
|
$this->headLink = $headLink; |
|
44
|
9 |
|
$this->options = $options; |
|
45
|
9 |
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* @param MvcEvent $event |
|
49
|
|
|
*/ |
|
50
|
8 |
|
public function __invoke(MvcEvent $event) |
|
51
|
|
|
{ |
|
52
|
8 |
|
$response = $event->getResponse(); |
|
53
|
8 |
|
if (! $response instanceof Response) { |
|
54
|
1 |
|
return; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
7 |
|
$values = []; |
|
58
|
|
|
|
|
59
|
7 |
|
foreach ($this->headLink->getContainer() as $item) { |
|
60
|
6 |
|
$attributes = \get_object_vars($item); |
|
61
|
|
|
|
|
62
|
6 |
|
if (! $this->canInjectLink($attributes)) { |
|
63
|
2 |
|
continue; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
6 |
|
if (! $this->options->isHttp2PushEnabled()) { |
|
67
|
3 |
|
$attributes['nopush'] = null; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
6 |
|
$values[] = $this->createLinkHeaderValue($attributes); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
7 |
|
$this->addLinkHeader($response, $values); |
|
74
|
7 |
|
} |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* Whether the link is valid to be injected in headers |
|
78
|
|
|
* |
|
79
|
|
|
* @param array $attributes |
|
80
|
|
|
* @return bool |
|
81
|
|
|
*/ |
|
82
|
6 |
|
private function canInjectLink(array $attributes): bool |
|
83
|
|
|
{ |
|
84
|
6 |
|
if (empty($attributes['href'] ?? '')) { |
|
85
|
1 |
|
return false; |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
6 |
|
return \in_array($attributes['rel'] ?? '', self::ALLOWED_RELS, true); |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
|