LinkHandler::__invoke()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

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