LinkHandler   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 68
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 68
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A __invoke() 0 25 5
A canInjectLink() 0 8 2
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