LinkHandler   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

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