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