Completed
Push — 8.x-1.x ( 35c1b8...518784 )
by
unknown
24:14
created

HttpCacheEventSubscriber::onKernelController()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
ccs 16
cts 16
cp 1
rs 8.5125
cc 5
eloc 14
nc 9
nop 1
crap 5
1
<?php
2
3
namespace Drupal\controller_annotations\EventSubscriber;
4
5
use Drupal\controller_annotations\Configuration\Cache;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
8
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
9
use Symfony\Component\HttpKernel\KernelEvents;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
12
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
13
14
class HttpCacheEventSubscriber implements EventSubscriberInterface
15
{
16
17
    /**
18
     * @var \SplObjectStorage
19
     */
20
    private $lastModifiedDates;
21
22
    /**
23
     * @var \SplObjectStorage
24
     */
25
    private $eTags;
26
27
    /**
28
     * @var ExpressionLanguage
29
     */
30
    private $expressionLanguage;
31
32
    /**
33
     */
34 20
    public function __construct()
35
    {
36 20
        $this->lastModifiedDates = new \SplObjectStorage();
37 20
        $this->eTags = new \SplObjectStorage();
38 20
    }
39
40
    /**
41
     * Handles HTTP validation headers.
42
     *
43
     * @param FilterControllerEvent $event
44
     */
45 11
    public function onKernelController(FilterControllerEvent $event)
46
    {
47 11
        $request = $event->getRequest();
48 11
        if (!$configuration = $request->attributes->get('_cache')) {
49 7
            return;
50
        }
51
52 4
        $response = new Response();
53
54 4
        if ($configuration->getLastModified()) {
55 2
            $this->setLastModified($request, $response, $configuration);
56
        }
57 4
        if ($configuration->getETag()) {
58 2
            $this->setETag($request, $response, $configuration);
59
        }
60 4
        if ($response->isNotModified($request)) {
61 2
            $event->setController(
62 2
              function () use ($response) {
63 2
                  return $response;
64 2
              }
65
            );
66 2
            $event->stopPropagation();
67
        }
68 4
    }
69
70
    /**
71
     * @param Request $request
72
     * @param Response $response
73
     * @param Cache $configuration
74
     */
75 2
    protected function setLastModified(
76
      Request $request,
77
      Response $response,
78
      Cache $configuration
79
    ) {
80 2
        $lastModifiedDate = $this->getExpressionLanguage()->evaluate(
81 2
          $configuration->getLastModified(),
82 2
          $request->attributes->all()
83
        );
84 2
        $response->setLastModified($lastModifiedDate);
0 ignored issues
show
Documentation introduced by
$lastModifiedDate is of type array, but the function expects a null|object<DateTime>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
85 2
        $this->lastModifiedDates[$request] = $lastModifiedDate;
86 2
    }
87
88
    /**
89
     * @param Request $request
90
     * @param Response $response
91
     * @param Cache $configuration
92
     */
93 2
    protected function setETag(
94
      Request $request,
95
      Response $response,
96
      Cache $configuration
97
    ) {
98 2
        $eTag = $this->createETag($request, $configuration);
99 2
        $response->setETag($eTag);
100 2
        $this->eTags[$request] = $eTag;
101 2
    }
102
103
    /**
104
     * @param Request $request
105
     * @param Cache $configuration
106
     *
107
     * @return string
108
     */
109 2
    protected function createETag(Request $request, Cache $configuration)
110
    {
111 2
        return hash(
112 2
          'sha256',
113 2
          $this->getExpressionLanguage()->evaluate(
114 2
            $configuration->getETag(),
115 2
            $request->attributes->all()
116
          )
117
        );
118
    }
119
120
    /**
121
     * Modifies the response to apply HTTP cache headers when needed.
122
     *
123
     * @param FilterResponseEvent $event
124
     */
125 18
    public function onKernelResponse(FilterResponseEvent $event)
126
    {
127 18
        $request = $event->getRequest();
128 18
        if (!$configuration = $request->attributes->get('_cache')) {
129 8
            return;
130
        }
131
132 10
        $response = $event->getResponse();
133 10
        if ($this->hasUncachableStatusCode($response)) {
134 1
            return;
135
        }
136
137 9 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...
138 2
            if (!is_numeric($age)) {
139 1
                $now = microtime(true);
140
141 1
                $age = ceil(
142 1
                  strtotime($configuration->getSMaxAge(), $now) - $now
143
                );
144
            }
145
146 2
            $response->setSharedMaxAge($age);
147
        }
148
149 9 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...
150 2
            if (!is_numeric($age)) {
151 1
                $now = microtime(true);
152
153 1
                $age = ceil(
154 1
                  strtotime($configuration->getMaxAge(), $now) - $now
155
                );
156
            }
157
158 2
            $response->setMaxAge($age);
159
        }
160
161 9
        if (null !== $configuration->getExpires()) {
162 1
            $date = \DateTime::createFromFormat(
163 1
              'U',
164 1
              strtotime($configuration->getExpires()),
165 1
              new \DateTimeZone('UTC')
166
            );
167 1
            $response->setExpires($date);
0 ignored issues
show
Security Bug introduced by
It seems like $date defined by \DateTime::createFromFor...w \DateTimeZone('UTC')) on line 162 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...
168
        }
169
170 9
        if (null !== $configuration->getVary()) {
171 1
            $response->setVary($configuration->getVary());
172
        }
173
174 9
        if ($configuration->isPublic()) {
175 1
            $response->setPublic();
176
        }
177
178 9
        if ($configuration->isPrivate()) {
179 1
            $response->setPrivate();
180
        }
181
182 9
        if (isset($this->lastModifiedDates[$request])) {
183 1
            $response->setLastModified($this->lastModifiedDates[$request]);
184
185 1
            unset($this->lastModifiedDates[$request]);
186
        }
187
188 9
        if (isset($this->eTags[$request])) {
189 1
            $response->setETag($this->eTags[$request]);
190
191 1
            unset($this->eTags[$request]);
192
        }
193 9
    }
194
195
    /**
196
     * http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-12#section-3.1
197
     *
198
     * @param Response $response
199
     *
200
     * @return bool
201
     */
202 10
    protected function hasUncachableStatusCode(Response $response)
203
    {
204 10
        if (!in_array(
205 10
          $response->getStatusCode(),
206 10
          [200, 203, 300, 301, 302, 304, 404, 410]
207
        )) {
208 1
            return true;
209
        }
210
211 9
        return false;
212
    }
213
214
    /**
215
     * @codeCoverageIgnore
216
     * @return ExpressionLanguage
217
     */
218
    private function getExpressionLanguage()
219
    {
220
        if (null === $this->expressionLanguage) {
221
            if (!class_exists(ExpressionLanguage::class)) {
222
                throw new \RuntimeException(
223
                  'Unable to use expressions as the Symfony ExpressionLanguage component is not installed.'
224
                );
225
            }
226
            $this->expressionLanguage = new ExpressionLanguage();
227
        }
228
229
        return $this->expressionLanguage;
230
    }
231
232
    /**
233
     * @return array
234
     */
235 7
    public static function getSubscribedEvents()
236
    {
237
        return [
238
          KernelEvents::CONTROLLER => [
239
            ['onKernelController', 0],
240 7
          ],
241
          KernelEvents::RESPONSE => [
242
            ['onKernelResponse', 100],
243
          ],
244
        ];
245
    }
246
}
247