Completed
Push — master ( 354506...449e75 )
by David
03:26
created

CacheControlListener::isRequestSafe()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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 = [
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 15
    public function __construct($debugHeader = false)
61
    {
62 15
        $this->debugHeader = $debugHeader;
63 15
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 23
    public static function getSubscribedEvents()
69
    {
70
        return [
71 23
            KernelEvents::RESPONSE => ['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
    public function setSkip($skip = true)
86
    {
87
        $this->skip = $skip;
88
    }
89
90
    /**
91
     * Apply the header rules if the request matches.
92
     *
93
     * @param FilterResponseEvent $event
94
     */
95 15
    public function onKernelResponse(FilterResponseEvent $event)
96
    {
97 15
        $request = $event->getRequest();
98 15
        $response = $event->getResponse();
99
100 15
        if ($this->debugHeader) {
101 15
            $response->headers->set($this->debugHeader, 1, false);
102
        }
103
104
        // do not change cache directives on unsafe requests.
105 15
        if ($this->skip || !$request->isMethodCacheable()) {
106 8
            return;
107
        }
108
109 7
        $options = $this->matchRule($request, $response);
110 7
        if (false !== $options) {
111 2
            if (!empty($options['cache_control'])) {
112 2
                $directives = array_intersect_key($options['cache_control'], $this->supportedDirectives);
113 2
                $extraDirectives = array_diff_key($options['cache_control'], $directives);
114 2
                if (!empty($directives)) {
115 2
                    $this->setCache($response, $directives, $options['overwrite']);
116
                }
117 2
                if (!empty($extraDirectives)) {
118
                    $this->setExtraCacheDirectives($response, $extraDirectives, $options['overwrite']);
119
                }
120
            }
121
122 2
            if (isset($options['reverse_proxy_ttl'])
123 2
                && null !== $options['reverse_proxy_ttl']
124 2
                && !$response->headers->has('X-Reverse-Proxy-TTL')
125
            ) {
126
                $response->headers->set('X-Reverse-Proxy-TTL', (int) $options['reverse_proxy_ttl'], false);
127
            }
128
129 2
            if (!empty($options['vary'])) {
130
                $response->setVary($options['vary'], $options['overwrite']);
131
            }
132
133 2
            if (!empty($options['etag'])
134 2
                && ($options['overwrite'] || null === $response->getEtag())
135
            ) {
136
                $response->setEtag(md5($response->getContent()));
137
            }
138 2
            if (isset($options['last_modified'])
139 2
                && ($options['overwrite'] || null === $response->getLastModified())
140
            ) {
141
                $response->setLastModified(new \DateTime($options['last_modified']));
142
            }
143
        }
144 7
    }
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 2
    private function setCache(Response $response, array $directives, $overwrite)
154
    {
155 2
        if ($overwrite) {
156
            $response->setCache($directives);
157
158
            return;
159
        }
160
161 2
        if (false !== strpos($response->headers->get('Cache-Control'), 'no-cache')) {
162
            // this single header is set by default. if its the only thing, we override it.
163 2
            $response->setCache($directives);
164
165 2
            return;
166
        }
167
168
        foreach (array_keys($this->supportedDirectives) as $key) {
169
            $directive = str_replace('_', '-', $key);
170
            if ($response->headers->hasCacheControlDirective($directive)) {
171
                $directives[$key] = $response->headers->getCacheControlDirective($directive);
172
            }
173
            if ('public' === $directive && $response->headers->hasCacheControlDirective('private')
174
                || 'private' === $directive && $response->headers->hasCacheControlDirective('public')
175
            ) {
176
                unset($directives[$key]);
177
            }
178
        }
179
180
        $response->setCache($directives);
181
    }
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
    private function setExtraCacheDirectives(Response $response, array $controls, $overwrite)
191
    {
192
        $flags = ['must_revalidate', 'proxy_revalidate', 'no_transform', 'no_cache'];
193
        $options = ['stale_if_error', 'stale_while_revalidate'];
194
195 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
            $flag = str_replace('_', '-', $key);
197
            if (!empty($controls[$key])
198
                && ($overwrite || !$response->headers->hasCacheControlDirective($flag))
199
            ) {
200
                $response->headers->addCacheControlDirective($flag);
201
            }
202
        }
203
204 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
            $option = str_replace('_', '-', $key);
206
            if (isset($controls[$key])
207
                && ($overwrite || !$response->headers->hasCacheControlDirective($option))
208
            ) {
209
                $response->headers->addCacheControlDirective($option, $controls[$key]);
210
            }
211
        }
212
    }
213
}
214