Completed
Pull Request — master (#275)
by
unknown
06:37
created

CacheControlSubscriber::setCache()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
ccs 20
cts 20
cp 1
rs 4.9091
cc 9
eloc 15
nc 7
nop 3
crap 9
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 CacheControlSubscriber extends AbstractRuleSubscriber 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 32
    public function __construct($debugHeader = false)
61
    {
62 32
        $this->debugHeader = $debugHeader;
63 32
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 23
    public static function getSubscribedEvents()
69
    {
70
        return array(
71 23
            KernelEvents::RESPONSE => array('onKernelResponse', 10),
72 23
        );
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 32
    public function onKernelResponse(FilterResponseEvent $event)
96
    {
97 32
        $request = $event->getRequest();
98 32
        $response = $event->getResponse();
99
100 32
        if ($this->debugHeader) {
101 16
            $response->headers->set($this->debugHeader, 1, false);
102 16
        }
103
104
105 32
        if ($this->skip) {
106 1
            return;
107
        }
108
109
        // do not change cache directives on unsafe requests.
110 31
        if ($request->getMethod() !== 'OPTIONS' &&
111 30
            !$this->isRequestSafe($request)
112 31
        ) {
113 9
            return;
114
        }
115
116 22
        $options = $this->matchRule($request, $response);
117 22
        if (false !== $options) {
118 16
            if (!empty($options['cache_control'])) {
119 11
                $directives = array_intersect_key($options['cache_control'], $this->supportedDirectives);
120 11
                $extraDirectives = array_diff_key($options['cache_control'], $directives);
121 11
                if (!empty($directives)) {
122 9
                    $this->setCache($response, $directives, $options['overwrite']);
123 9
                }
124 11
                if (!empty($extraDirectives)) {
125 6
                    $this->setExtraCacheDirectives($response, $extraDirectives, $options['overwrite']);
126 6
                }
127 11
            }
128
129 16
            if (isset($options['reverse_proxy_ttl'])
130 16
                && null !== $options['reverse_proxy_ttl']
131 16
                && !$response->headers->has('X-Reverse-Proxy-TTL')
132 16
            ) {
133 1
                $response->headers->set('X-Reverse-Proxy-TTL', (int) $options['reverse_proxy_ttl'], false);
134 1
            }
135
136 16
            if (!empty($options['vary'])) {
137 3
                $response->setVary($options['vary'], $options['overwrite']);
138 3
            }
139
140 16
            if (!empty($options['etag'])
141 16
                && ($options['overwrite'] || null === $response->getEtag())
142 16
            ) {
143 1
                $response->setEtag(md5($response->getContent()));
144 1
            }
145 16
            if (isset($options['last_modified'])
146 16
                && ($options['overwrite'] || null === $response->getLastModified())
147 16
            ) {
148 3
                $response->setLastModified(new \DateTime($options['last_modified']));
149 3
            }
150 16
        }
151 22
    }
152
153
    /**
154
     * Set cache headers on response.
155
     *
156
     * @param Response $response
157
     * @param array    $directives
158
     * @param boolean  $overwrite  Whether to keep existing cache headers or to overwrite them.
159
     */
160 9
    private function setCache(Response $response, array $directives, $overwrite)
161
    {
162 9
        if ($overwrite) {
163 1
            $response->setCache($directives);
164
165 1
            return;
166
        }
167
168 8
        if ('no-cache' === $response->headers->get('cache-control')) {
169
            // this single header is set by default. if its the only thing, we override it.
170 6
            $response->setCache($directives);
171
172 6
            return;
173
        }
174
175 2
        foreach (array_keys($this->supportedDirectives) as $key) {
176 2
            $directive = str_replace('_', '-', $key);
177 2
            if ($response->headers->hasCacheControlDirective($directive)) {
178 2
                $directives[$key] = $response->headers->getCacheControlDirective($directive);
179 2
            }
180 2
            if ('public' === $directive && $response->headers->hasCacheControlDirective('private')
181 2
                || 'private' === $directive && $response->headers->hasCacheControlDirective('public')
182 2
            ) {
183 2
                unset($directives[$key]);
184 2
            }
185 2
        }
186
187 2
        $response->setCache($directives);
188 2
    }
189
190
    /**
191
     * Add extra cache control directives.
192
     *
193
     * @param Response $response
194
     * @param array    $controls
195
     * @param boolean  $overwrite Whether to keep existing cache headers or to overwrite them.
196
     */
197 6
    private function setExtraCacheDirectives(Response $response, array $controls, $overwrite)
198
    {
199 6
        $flags = array('must_revalidate', 'proxy_revalidate', 'no_transform', 'no_cache');
200 6
        $options = array('stale_if_error', 'stale_while_revalidate');
201
202 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...
203 6
            $flag = str_replace('_', '-', $key);
204 6
            if (!empty($controls[$key])
205 6
                && ($overwrite || !$response->headers->hasCacheControlDirective($flag))
206 6
            ) {
207 5
                $response->headers->addCacheControlDirective($flag);
208 5
            }
209 6
        }
210
211 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...
212 6
            $option = str_replace('_', '-', $key);
213 6
            if (isset($controls[$key])
214 6
                && ($overwrite || !$response->headers->hasCacheControlDirective($option))
215 6
            ) {
216 4
                $response->headers->addCacheControlDirective($option, $controls[$key]);
217 4
            }
218 6
        }
219 6
    }
220
221
    /**
222
     * Decide whether to even look for matching rules with the current request.
223
     *
224
     * @param Request $request
225
     *
226
     * @return bool True if the request is safe and headers can be set.
227
     */
228 30
    protected function isRequestSafe(Request $request)
229
    {
230 30
        return $request->isMethodSafe();
231
    }
232
}
233