ScriptHandler::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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\HeadScript;
13
14
final class ScriptHandler extends AbstractLinkHandler
15
{
16
    /**
17
     * @var HeadScript
18
     */
19
    private $headScript;
20
21
    /**
22
     * @var OptionsInterface
23
     */
24
    private $options;
25
26 6
    public function __construct(HeadScript $headScript, OptionsInterface $options)
27
    {
28 6
        $this->headScript = $headScript;
29 6
        $this->options = $options;
30 6
    }
31
32 5
    public function __invoke(MvcEvent $event): void
33
    {
34 5
        if (! $this->options->isScriptEnabled()) {
35 1
            return;
36
        }
37
38 4
        $response = $event->getResponse();
39 4
        if (! $response instanceof Response) {
40 1
            return;
41
        }
42
43 3
        $values = [];
44
45 3
        foreach ($this->headScript->getContainer() as $item) {
46 3
            $properties = get_object_vars($item);
47 3
            $attributes = $properties['attributes'] ?? [];
48
49 3
            if (! $this->canInjectLink($attributes)) {
50 3
                continue;
51
            }
52
53
            $attributes = [
54 3
                'href' => $attributes['src'],
55 3
                'rel' => $this->options->getScriptMode(),
56 3
                'as' => 'script',
57 3
                'type' => $properties['type'] ?? null,
58
            ];
59
60 3
            $attributes = array_filter($attributes);
61
62 3
            if (! $this->options->isHttp2PushEnabled()) {
63 2
                $attributes['nopush'] = null;
64
            }
65
66 3
            $values[] = $this->createLinkHeaderValue($attributes);
67
        }
68
69 3
        $this->addLinkHeader($response, $values);
70 3
    }
71
72
    /**
73
     * Whether the link is valid to be injected in headers
74
     *
75
     * @param array<string, mixed> $attributes
76
     *
77
     * @return bool
78
     */
79 3
    private function canInjectLink(array $attributes): bool
80
    {
81 3
        return ! empty($attributes['src'] ?? '');
82
    }
83
}
84