ScriptHandler   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 4
dl 0
loc 78
ccs 28
cts 28
cp 1
rs 10
c 0
b 0
f 0

3 Methods

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