Completed
Push — 8.x-1.x ( 082f3b...0421f5 )
by
unknown
28:58 queued 09:33
created

HttpCacheEventSubscriber::onKernelResponse()   F

Complexity

Conditions 13
Paths 578

Size

Total Lines 64
Code Lines 32

Duplication

Lines 18
Ratio 28.13 %

Code Coverage

Tests 4
CRAP Score 127.6982

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 18
loc 64
ccs 4
cts 33
cp 0.1212
rs 3.2968
cc 13
eloc 32
nc 578
nop 1
crap 127.6982

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Drupal\controller_annotations\EventSubscriber;
4
5
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
6
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
7
use Symfony\Component\HttpKernel\KernelEvents;
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
10
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
11
12
class HttpCacheEventSubscriber implements EventSubscriberInterface
13
{
14
15
    /**
16
     * @var \SplObjectStorage
17
     */
18
    private $lastModifiedDates;
19
20
    /**
21
     * @var \SplObjectStorage
22
     */
23
    private $etags;
24
25
    /**
26
     * @var ExpressionLanguage
27
     */
28
    private $expressionLanguage;
29
30
    /**
31
     */
32 6
    public function __construct()
33
    {
34 6
        $this->lastModifiedDates = new \SplObjectStorage();
35 6
        $this->etags = new \SplObjectStorage();
36 6
    }
37
38
    /**
39
     * Handles HTTP validation headers.
40
     *
41
     * @param FilterControllerEvent $event
42
     */
43 6
    public function onKernelController(FilterControllerEvent $event)
44
    {
45 6
        $request = $event->getRequest();
46 6
        if (!$configuration = $request->attributes->get('_cache')) {
47 6
            return;
48
        }
49
50
        $response = new Response();
51
52
        $lastModifiedDate = '';
53
        if ($configuration->getLastModified()) {
54
            $lastModifiedDate = $this->getExpressionLanguage()->evaluate($configuration->getLastModified(), $request->attributes->all());
55
            $response->setLastModified($lastModifiedDate);
56
        }
57
58
        $etag = '';
59
        if ($configuration->getETag()) {
60
            $etag = hash('sha256', $this->getExpressionLanguage()->evaluate($configuration->getETag(), $request->attributes->all()));
61
            $response->setETag($etag);
62
        }
63
64
        if ($response->isNotModified($request)) {
65
            $event->setController(function () use ($response) {
66
                return $response;
67
            });
68
            $event->stopPropagation();
69
        } else {
70
            if ($etag) {
71
                $this->etags[$request] = $etag;
72
            }
73
            if ($lastModifiedDate) {
74
                $this->lastModifiedDates[$request] = $lastModifiedDate;
75
            }
76
        }
77
    }
78
79
    /**
80
     * Modifies the response to apply HTTP cache headers when needed.
81
     *
82
     * @param FilterResponseEvent $event
83
     */
84 6
    public function onKernelResponse(FilterResponseEvent $event)
85
    {
86 6
        $request = $event->getRequest();
87
88 6
        if (!$configuration = $request->attributes->get('_cache')) {
89 6
            return;
90
        }
91
92
        $response = $event->getResponse();
93
94
        // http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-12#section-3.1
95
        if (!in_array($response->getStatusCode(), array(200, 203, 300, 301, 302, 304, 404, 410))) {
96
            return;
97
        }
98
99 View Code Duplication
        if (null !== $age = $configuration->getSMaxAge()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
100
            if (!is_numeric($age)) {
101
                $now = microtime(true);
102
103
                $age = ceil(strtotime($configuration->getSMaxAge(), $now) - $now);
104
            }
105
106
            $response->setSharedMaxAge($age);
107
        }
108
109 View Code Duplication
        if (null !== $age = $configuration->getMaxAge()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
            if (!is_numeric($age)) {
111
                $now = microtime(true);
112
113
                $age = ceil(strtotime($configuration->getMaxAge(), $now) - $now);
114
            }
115
116
            $response->setMaxAge($age);
117
        }
118
119
        if (null !== $configuration->getExpires()) {
120
            $date = \DateTime::createFromFormat('U', strtotime($configuration->getExpires()), new \DateTimeZone('UTC'));
121
            $response->setExpires($date);
0 ignored issues
show
Security Bug introduced by
It seems like $date defined by \DateTime::createFromFor...w \DateTimeZone('UTC')) on line 120 can also be of type false; however, Symfony\Component\HttpFo...\Response::setExpires() does only seem to accept null|object<DateTime>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
122
        }
123
124
        if (null !== $configuration->getVary()) {
125
            $response->setVary($configuration->getVary());
126
        }
127
128
        if ($configuration->isPublic()) {
129
            $response->setPublic();
130
        }
131
132
        if ($configuration->isPrivate()) {
133
            $response->setPrivate();
134
        }
135
136
        if (isset($this->lastModifiedDates[$request])) {
137
            $response->setLastModified($this->lastModifiedDates[$request]);
138
139
            unset($this->lastModifiedDates[$request]);
140
        }
141
142
        if (isset($this->etags[$request])) {
143
            $response->setETag($this->etags[$request]);
144
145
            unset($this->etags[$request]);
146
        }
147
    }
148
149
    /**
150
     * @return ExpressionLanguage
151
     */
152
    private function getExpressionLanguage()
153
    {
154
        if (null === $this->expressionLanguage) {
155
            if (!class_exists(ExpressionLanguage::class)) {
156
                throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
157
            }
158
            $this->expressionLanguage = new ExpressionLanguage();
159
        }
160
161
        return $this->expressionLanguage;
162
    }
163
164
    /**
165
     * @return array
166
     */
167 6
    public static function getSubscribedEvents()
168
    {
169
        return [
170
            KernelEvents::CONTROLLER => [
171
                ['onKernelController', 0],
172 6
            ],
173
            KernelEvents::RESPONSE => [
174
                ['onKernelResponse', 100],
175
            ],
176
        ];
177
    }
178
}
179