Completed
Push — master ( 0de349...246355 )
by David
13s
created

src/EventListener/CacheControlListener.php (1 issue)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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\HttpFoundation\Request;
16
use Symfony\Component\HttpFoundation\Response;
17
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
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 30
    public function __construct($debugHeader = false)
61
    {
62 30
        $this->debugHeader = $debugHeader;
63 30
    }
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 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 30
    public function onKernelResponse(FilterResponseEvent $event)
96
    {
97 30
        $request = $event->getRequest();
98 30
        $response = $event->getResponse();
99
100 30
        if ($this->debugHeader) {
101 16
            $response->headers->set($this->debugHeader, 1, false);
102
        }
103
104
        // do not change cache directives on unsafe requests.
105 30
        if ($this->skip || !$request->isMethodCacheable()) {
106 10
            return;
107
        }
108
109 20
        $options = $this->matchRule($request, $response);
0 ignored issues
show
The call to CacheControlListener::matchRule() has too many arguments starting with $response.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
110 20
        if (false !== $options) {
111 14
            if (!empty($options['cache_control'])) {
112 12
                $directives = array_intersect_key($options['cache_control'], $this->supportedDirectives);
113 12
                $extraDirectives = array_diff_key($options['cache_control'], $directives);
114 12
                if (!empty($directives)) {
115 9
                    $this->setCache($response, $directives, $options['overwrite']);
116
                }
117 12
                if (!empty($extraDirectives)) {
118 7
                    $this->setExtraCacheDirectives($response, $extraDirectives, $options['overwrite']);
119
                }
120
            }
121
122 14
            if (isset($options['reverse_proxy_ttl'])
123 14
                && null !== $options['reverse_proxy_ttl']
124 14
                && !$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 14
            if (!empty($options['vary'])) {
130 3
                $response->setVary($options['vary'], $options['overwrite']);
131
            }
132
133 14
            if (!empty($options['etag'])
134 14
                && ($options['overwrite'] || null === $response->getEtag())
135
            ) {
136 1
                $response->setEtag(md5($response->getContent()));
137
            }
138 14
            if (isset($options['last_modified'])
139 14
                && ($options['overwrite'] || null === $response->getLastModified())
140
            ) {
141 3
                $response->setLastModified(new \DateTime($options['last_modified']));
142
            }
143
        }
144 20
    }
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 (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 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 7
    private function setExtraCacheDirectives(Response $response, array $controls, $overwrite)
191
    {
192 7
        $flags = ['must_revalidate', 'proxy_revalidate', 'no_transform', 'no_cache', 'no_store'];
193 7
        $options = ['stale_if_error', 'stale_while_revalidate'];
194
195 7 View Code Duplication
        foreach ($flags as $key) {
196 7
            $flag = str_replace('_', '-', $key);
197 7
            if (!empty($controls[$key])
198 7
                && ($overwrite || !$response->headers->hasCacheControlDirective($flag))
199
            ) {
200 7
                $response->headers->addCacheControlDirective($flag);
201
            }
202
        }
203
204 7 View Code Duplication
        foreach ($options as $key) {
205 7
            $option = str_replace('_', '-', $key);
206 7
            if (isset($controls[$key])
207 7
                && ($overwrite || !$response->headers->hasCacheControlDirective($option))
208
            ) {
209 7
                $response->headers->addCacheControlDirective($option, $controls[$key]);
210
            }
211
        }
212 7
    }
213
}
214