Completed
Push — 8.x-1.x ( 99c4c7...dece3c )
by
unknown
29:31
created

HttpCacheEventSubscriber::getExpressionLanguage()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
ccs 0
cts 0
cp 0
rs 9.4285
cc 3
eloc 6
nc 3
nop 0
crap 12
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 19
    public function __construct()
33
    {
34 19
        $this->lastModifiedDates = new \SplObjectStorage();
35 19
        $this->eTags = new \SplObjectStorage();
36 19
    }
37
38
    /**
39
     * Handles HTTP validation headers.
40
     *
41
     * @param FilterControllerEvent $event
42
     */
43 10
    public function onKernelController(FilterControllerEvent $event)
44
    {
45 10
        $request = $event->getRequest();
46 10
        if (!$configuration = $request->attributes->get('_cache')) {
47 6
            return;
48
        }
49
50 4
        $response = new Response();
51
52 4
        $lastModifiedDate = '';
53 4
        if ($configuration->getLastModified()) {
54 2
            $lastModifiedDate = $this->getExpressionLanguage()->evaluate($configuration->getLastModified(), $request->attributes->all());
55 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...
56
        }
57
58 4
        $eTag = '';
59 4
        if ($configuration->getETag()) {
60 2
            $eTag = hash('sha256', $this->getExpressionLanguage()->evaluate($configuration->getETag(), $request->attributes->all()));
61 2
            $response->setETag($eTag);
62
        }
63
64 4
        if ($response->isNotModified($request)) {
65 2
            $event->setController(function () use ($response) {
66 2
                return $response;
67 2
            });
68 2
            $event->stopPropagation();
69
        } else {
70 2
            if ($eTag) {
71 1
                $this->eTags[$request] = $eTag;
72
            }
73 2
            if ($lastModifiedDate) {
74 1
                $this->lastModifiedDates[$request] = $lastModifiedDate;
75
            }
76
        }
77 4
    }
78
79
    /**
80
     * Modifies the response to apply HTTP cache headers when needed.
81
     *
82
     * @param FilterResponseEvent $event
83
     */
84 17
    public function onKernelResponse(FilterResponseEvent $event)
85
    {
86 17
        $request = $event->getRequest();
87
88 17
        if (!$configuration = $request->attributes->get('_cache')) {
89 7
            return;
90
        }
91
92 10
        $response = $event->getResponse();
93
94
        // http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-12#section-3.1
95 10
        if (!in_array($response->getStatusCode(), array(200, 203, 300, 301, 302, 304, 404, 410))) {
96 1
            return;
97
        }
98
99 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...
100 2
            if (!is_numeric($age)) {
101 1
                $now = microtime(true);
102
103 1
                $age = ceil(strtotime($configuration->getSMaxAge(), $now) - $now);
104
            }
105
106 2
            $response->setSharedMaxAge($age);
107
        }
108
109 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...
110 2
            if (!is_numeric($age)) {
111 1
                $now = microtime(true);
112
113 1
                $age = ceil(strtotime($configuration->getMaxAge(), $now) - $now);
114
            }
115
116 2
            $response->setMaxAge($age);
117
        }
118
119 9
        if (null !== $configuration->getExpires()) {
120 1
            $date = \DateTime::createFromFormat('U', strtotime($configuration->getExpires()), new \DateTimeZone('UTC'));
121 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 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 9
        if (null !== $configuration->getVary()) {
125 1
            $response->setVary($configuration->getVary());
126
        }
127
128 9
        if ($configuration->isPublic()) {
129 1
            $response->setPublic();
130
        }
131
132 9
        if ($configuration->isPrivate()) {
133 1
            $response->setPrivate();
134
        }
135
136 9
        if (isset($this->lastModifiedDates[$request])) {
137 1
            $response->setLastModified($this->lastModifiedDates[$request]);
138
139 1
            unset($this->lastModifiedDates[$request]);
140
        }
141
142 9
        if (isset($this->eTags[$request])) {
143 1
            $response->setETag($this->eTags[$request]);
144
145 1
            unset($this->eTags[$request]);
146
        }
147 9
    }
148
149
    /**
150
     * @codeCoverageIgnore
151
     * @return ExpressionLanguage
152
     */
153
    private function getExpressionLanguage()
154
    {
155
        if (null === $this->expressionLanguage) {
156
            if (!class_exists(ExpressionLanguage::class)) {
157
                throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
158
            }
159
            $this->expressionLanguage = new ExpressionLanguage();
160
        }
161
162
        return $this->expressionLanguage;
163
    }
164
165
    /**
166
     * @return array
167
     */
168 6
    public static function getSubscribedEvents()
169
    {
170
        return [
171
            KernelEvents::CONTROLLER => [
172
                ['onKernelController', 0],
173 6
            ],
174
            KernelEvents::RESPONSE => [
175
                ['onKernelResponse', 100],
176
            ],
177
        ];
178
    }
179
}
180