Completed
Push — master ( 9bb55b...536c73 )
by David de
11s
created

CacheControlListener::onKernelResponse()   D

Complexity

Conditions 18
Paths 164

Size

Total Lines 50
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 18

Importance

Changes 0
Metric Value
dl 0
loc 50
ccs 29
cts 29
cp 1
rs 4.9801
c 0
b 0
f 0
cc 18
eloc 28
nc 164
nop 1
crap 18

How to fix   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
/*
4
 * This file is part of the FOSHttpCacheBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\HttpCacheBundle\EventListener;
13
14
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
15
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
16
use Symfony\Component\HttpFoundation\Response;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpKernel\KernelEvents;
19
20
/**
21
 * Set caching settings on matching response according to the configurations.
22
 *
23
 * The first matching ruleset is applied.
24
 *
25
 * @author Lea Haensenberger <[email protected]>
26
 * @author David Buchmann <[email protected]>
27
 */
28
class CacheControlListener extends AbstractRuleListener implements EventSubscriberInterface
29
{
30
    /**
31
     * Whether to skip this response and not set any cache headers.
32
     *
33
     * @var bool
34
     */
35
    private $skip = false;
36
37
    /**
38
     * Cache control directives directly supported by Response.
39
     *
40
     * @var array
41
     */
42
    private $supportedDirectives = array(
43
        'max_age' => true,
44
        's_maxage' => true,
45
        'private' => true,
46
        'public' => true,
47
    );
48
49
    /**
50
     * If not empty, add a debug header with that name to all responses,
51
     * telling the cache proxy to add debug output.
52
     *
53
     * @var string|bool Name of the header or false to add no header
54
     */
55
    private $debugHeader;
56
57
    /**
58
     * @param string|bool $debugHeader Header to set to trigger debugging, or false to send no header
59
     */
60 29
    public function __construct($debugHeader = false)
61
    {
62 29
        $this->debugHeader = $debugHeader;
63 29
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 23
    public static function getSubscribedEvents()
69
    {
70
        return array(
71 23
            KernelEvents::RESPONSE => array('onKernelResponse', 10),
72
        );
73
    }
74
75
    /**
76
     * Set whether to skip this response completely.
77
     *
78
     * This can be called when other parts of the application took care of all
79
     * cache headers. No attempt to merge cache headers is made anymore.
80
     *
81
     * The debug header is still added if configured.
82
     *
83
     * @param bool $skip
84
     */
85 1
    public function setSkip($skip = true)
86
    {
87 1
        $this->skip = $skip;
88 1
    }
89
90
    /**
91
     * Apply the header rules if the request matches.
92
     *
93
     * @param FilterResponseEvent $event
94
     */
95 29
    public function onKernelResponse(FilterResponseEvent $event)
96
    {
97 29
        $request = $event->getRequest();
98 29
        $response = $event->getResponse();
99
100 29
        if ($this->debugHeader) {
101 16
            $response->headers->set($this->debugHeader, 1, false);
102
        }
103
104
        // do not change cache directives on unsafe requests.
105 29
        if ($this->skip || !$this->isRequestSafe($request)) {
106 10
            return;
107
        }
108
109 19
        $options = $this->matchRule($request, $response);
110 19
        if (false !== $options) {
111 13
            if (!empty($options['cache_control'])) {
112 11
                $directives = array_intersect_key($options['cache_control'], $this->supportedDirectives);
113 11
                $extraDirectives = array_diff_key($options['cache_control'], $directives);
114 11
                if (!empty($directives)) {
115 9
                    $this->setCache($response, $directives, $options['overwrite']);
116
                }
117 11
                if (!empty($extraDirectives)) {
118 6
                    $this->setExtraCacheDirectives($response, $extraDirectives, $options['overwrite']);
119
                }
120
            }
121
122 13
            if (isset($options['reverse_proxy_ttl'])
123 13
                && null !== $options['reverse_proxy_ttl']
124 13
                && !$response->headers->has('X-Reverse-Proxy-TTL')
125
            ) {
126 1
                $response->headers->set('X-Reverse-Proxy-TTL', (int) $options['reverse_proxy_ttl'], false);
127
            }
128
129 13
            if (!empty($options['vary'])) {
130 3
                $response->setVary($options['vary'], $options['overwrite']);
131
            }
132
133 13
            if (!empty($options['etag'])
134 13
                && ($options['overwrite'] || null === $response->getEtag())
135
            ) {
136 1
                $response->setEtag(md5($response->getContent()));
137
            }
138 13
            if (isset($options['last_modified'])
139 13
                && ($options['overwrite'] || null === $response->getLastModified())
140
            ) {
141 3
                $response->setLastModified(new \DateTime($options['last_modified']));
142
            }
143
        }
144 19
    }
145
146
    /**
147
     * Set cache headers on response.
148
     *
149
     * @param Response $response
150
     * @param array    $directives
151
     * @param bool     $overwrite  Whether to keep existing cache headers or to overwrite them
152
     */
153 9
    private function setCache(Response $response, array $directives, $overwrite)
154
    {
155 9
        if ($overwrite) {
156 1
            $response->setCache($directives);
157
158 1
            return;
159
        }
160
161 8
        if ('no-cache' === $response->headers->get('cache-control')) {
162
            // this single header is set by default. if its the only thing, we override it.
163 6
            $response->setCache($directives);
164
165 6
            return;
166
        }
167
168 2
        foreach (array_keys($this->supportedDirectives) as $key) {
169 2
            $directive = str_replace('_', '-', $key);
170 2
            if ($response->headers->hasCacheControlDirective($directive)) {
171 2
                $directives[$key] = $response->headers->getCacheControlDirective($directive);
172
            }
173 2
            if ('public' === $directive && $response->headers->hasCacheControlDirective('private')
174 2
                || 'private' === $directive && $response->headers->hasCacheControlDirective('public')
175
            ) {
176 2
                unset($directives[$key]);
177
            }
178
        }
179
180 2
        $response->setCache($directives);
181 2
    }
182
183
    /**
184
     * Add extra cache control directives.
185
     *
186
     * @param Response $response
187
     * @param array    $controls
188
     * @param bool     $overwrite Whether to keep existing cache headers or to overwrite them
189
     */
190 6
    private function setExtraCacheDirectives(Response $response, array $controls, $overwrite)
191
    {
192 6
        $flags = array('must_revalidate', 'proxy_revalidate', 'no_transform', 'no_cache');
193 6
        $options = array('stale_if_error', 'stale_while_revalidate');
194
195 6 View Code Duplication
        foreach ($flags as $key) {
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...
196 6
            $flag = str_replace('_', '-', $key);
197 6
            if (!empty($controls[$key])
198 6
                && ($overwrite || !$response->headers->hasCacheControlDirective($flag))
199
            ) {
200 6
                $response->headers->addCacheControlDirective($flag);
201
            }
202
        }
203
204 6 View Code Duplication
        foreach ($options as $key) {
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...
205 6
            $option = str_replace('_', '-', $key);
206 6
            if (isset($controls[$key])
207 6
                && ($overwrite || !$response->headers->hasCacheControlDirective($option))
208
            ) {
209 6
                $response->headers->addCacheControlDirective($option, $controls[$key]);
210
            }
211
        }
212 6
    }
213
214
    /**
215
     * Decide whether to even look for matching rules with the current request.
216
     *
217
     * @param Request $request
218
     *
219
     * @return bool True if the request is safe and headers can be set
220
     */
221 28
    protected function isRequestSafe(Request $request)
222
    {
223 28
        return $request->isMethodSafe();
224
    }
225
}
226