Skip to content

Commit

Permalink
cleanup cache header overwrite options
Browse files Browse the repository at this point in the history
  • Loading branch information
dbu committed Oct 14, 2014
1 parent b70537b commit 233420c
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 54 deletions.
5 changes: 3 additions & 2 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,10 @@ private function addCacheControlSection(ArrayNodeDefinition $rootNode)
->fixXmlConfig('rule')
->children()
->arrayNode('defaults')
->addDefaultsIfNotSet()
->children()
->booleanNode('overwrite')
->info('Default behaviour for cache headers overwriting')
->info('Whether to overwrite existing cache headers')
->defaultFalse()
->end()
->end()
Expand All @@ -167,7 +168,7 @@ private function addCacheControlSection(ArrayNodeDefinition $rootNode)
// todo validate there is some header defined
->children()
->enumNode('overwrite')
->info('Overrides default cache headers overwrite behaviour')
->info('Whether to overwrite cache headers for this rule, defaults to the cache_control.defaults.overwrite setting')
->values(array('default', true, false))
->defaultValue('default')
->end()
Expand Down
7 changes: 3 additions & 4 deletions DependencyInjection/FOSHttpCacheExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,11 @@ private function loadCacheControl(ContainerBuilder $container, array $config)
foreach ($config['rules'] as $rule) {
$ruleMatcher = $this->parseRuleMatcher($container, $rule['match']);

if ($rule['headers']['defaults']['overwrite'] === 'default') {
$rule['headers']['defaults']['overwrite'] = $config['defaults']['overwrite'];
if ('default' === $rule['headers']['overwrite']) {
$rule['headers']['overwrite'] = $config['defaults']['overwrite'];
}

$controlDefinition->addMethodCall('addRule', array($ruleMatcher, $rule['headers']))
;
$controlDefinition->addMethodCall('addRule', array($ruleMatcher, $rule['headers']));
}
}

Expand Down
22 changes: 12 additions & 10 deletions EventListener/CacheControlSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@ public function onKernelResponse(FilterResponseEvent $event)
$directives = array_intersect_key($options['cache_control'], $this->supportedDirectives);
$extraDirectives = array_diff_key($options['cache_control'], $directives);
if (!empty($directives)) {
$this->setCache($response, $directives, $options['defaults']['overwrite']);
$this->setCache($response, $directives, $options['overwrite']);
}
if (!empty($extraDirectives)) {
$this->setExtraCacheDirectives($response, $extraDirectives, $options['defaults']['overwrite']);
$this->setExtraCacheDirectives($response, $extraDirectives, $options['overwrite']);
}
}

Expand All @@ -127,21 +127,23 @@ public function onKernelResponse(FilterResponseEvent $event)
}

if (!empty($options['vary'])) {
$response->setVary(array_merge($response->getVary(), $options['vary']), true); //update if already has vary
$response->setVary($options['vary'], $options['overwrite']);
}

if (isset($options['last_modified']) && null === $response->getLastModified()) {
if (isset($options['last_modified'])
&& ($options['overwrite'] || null === $response->getLastModified())
) {
$response->setLastModified(new \DateTime($options['last_modified']));
}
}
}

/**
* Set cache headers
* Set cache headers on response.
*
* @param Response $response
* @param array $directives
* @param boolean $overwrite
* @param boolean $overwrite Whether to keep existing cache headers or to overwrite them.
*/
private function setCache(Response $response, array $directives, $overwrite)
{
Expand Down Expand Up @@ -178,7 +180,7 @@ private function setCache(Response $response, array $directives, $overwrite)
*
* @param Response $response
* @param array $controls
* @param boolean $overwrite
* @param boolean $overwrite Whether to keep existing cache headers or to overwrite them.
*/
private function setExtraCacheDirectives(Response $response, array $controls, $overwrite)
{
Expand All @@ -190,16 +192,16 @@ private function setExtraCacheDirectives(Response $response, array $controls, $o
if (!empty($controls[$key])
&& ($overwrite || !$response->headers->hasCacheControlDirective($flag))
) {
$response->headers->addCacheControlDirective($flag);
$response->headers->addCacheControlDirective($flag);
}
}

foreach ($options as $key) {
$option = str_replace('_', '-', $key);
if (isset($controls[$key])
&& ($overwrite || !$response->headers->hasCacheControlDirective($option) )
&& ($overwrite || !$response->headers->hasCacheControlDirective($option))
) {
$response->headers->addCacheControlDirective($option, $controls[$key]);
$response->headers->addCacheControlDirective($option, $controls[$key]);

}
}
Expand Down
14 changes: 8 additions & 6 deletions Resources/doc/features/headers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ Set caching headers under the ``cache_control`` configuration section,
which consists of a set of rules. When the request matches all criteria under
``match``, the headers under ``headers`` will be set on the response.

By default cache headers are not overwritten if already set.
Header overwrite can be forced either globally, setting ``defaults`` ``overwrite`` to true,
or on a per rule basis setting ``overwrite`` to true under ``headers`` settings.
A Response may already have cache headers set, e.g. by the controller method.
By default, the options that already exist are not overwritten, but additional
headers are added. You can force to overwrite the headers globally by setting
``cache_control.defaults.overwrite: true`` to true, or on a per rule basis with
``overwrite: true`` under ``headers``.

For instance:

Expand All @@ -23,14 +25,13 @@ For instance:
fos_http_cache:
cache_control:
defaults:
overwrite: false
overwrite: true
rules:
# only match login.example.com
-
match:
host: ^login.example.com$
headers:
overwrite: true
cache_control: { public: false, max_age: 0, s_maxage: 0 }
last_modified: "-1 hour"
vary: [Accept-Encoding, Accept-Language]
Expand All @@ -55,8 +56,9 @@ For instance:
# match everything to set defaults
-
match:
path: ^/
path: ^/
headers:
overwrite: false
cache_control: { public: true, max_age: 15, s_maxage: 30 }
last_modified: "-1 hour"
Expand Down
2 changes: 1 addition & 1 deletion Resources/doc/reference/configuration/headers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ parameters described in the ``match`` section, the headers as defined under
``headers`` will be set on the response, if they are not already set. Rules are
checked in the order specified, where the first match wins.

A global setting and a per rule basis ``overwrite`` setting allows to overwrite the
A global setting and a per rule ``overwrite`` option allow to overwrite the
cache headers even if they are already set.

.. code-block:: yaml
Expand Down
114 changes: 83 additions & 31 deletions Tests/Unit/EventListener/CacheControlSubscriberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,20 @@ public function testExtraHeaders()
public function testCompoundHeaders()
{
$event = $this->buildEvent();
$headers = array('overwrite' => false,
'cache_control' => array(
'max_age' => '900',
's_maxage' => '300',
'public' => true,
'private' => false,
'must_revalidate' => true,
'proxy_revalidate' => true,
'no_transform' => true,
'stale_if_error' => '300',
'stale_while_revalidate' => '400',
));
$headers = array(
'overwrite' => false,
'cache_control' => array(
'max_age' => '900',
's_maxage' => '300',
'public' => true,
'private' => false,
'must_revalidate' => true,
'proxy_revalidate' => true,
'no_transform' => true,
'stale_if_error' => '300',
'stale_while_revalidate' => '400',
)
);
$subscriber = $this->getCacheControl($headers);

$subscriber->onKernelResponse($event);
Expand Down Expand Up @@ -108,35 +110,82 @@ public function testSetNoCacheHeaders()
public function testMergeHeaders()
{
$event = $this->buildEvent();
$headers = array('overwrite' => false,
'cache_control' => array(
'max_age' => '900',
's_maxage' => '300',
'public' => true,
'private' => false,
'must_revalidate' => true,
'proxy_revalidate' => true,
'no_transform' => true,
'stale_if_error' => '300',
'stale_while_revalidate' => '400',
));
$headers = array(
'overwrite' => false,
'cache_control' => array(
'max_age' => '900',
's_maxage' => '300',
'public' => true,
'private' => false,
'must_revalidate' => true,
'proxy_revalidate' => true,
'no_transform' => true,
'stale_if_error' => '300',
'stale_while_revalidate' => '400',
),
'vary' => array(
'Cookie',
),
'last_modified' => '2014-10-10 GMT',
);
$subscriber = $this->getCacheControl($headers);
$response = $event->getResponse();
$response->setPublic();
$response->setCache(array('max_age' => 0));
$response->headers->addCacheControlDirective('stale-if-error', 0);
$response->setVary('Encoding');
$response->setLastModified(new \DateTime('2013-09-09 GMT'));

$subscriber->onKernelResponse($event);
$newHeaders = $event->getResponse()->headers->all();

$this->assertEquals('max-age=0, must-revalidate, no-transform, proxy-revalidate, public, s-maxage=300, stale-if-error=0, stale-while-revalidate=400', $newHeaders['cache-control'][0]);
$this->assertEquals(array('Encoding', 'Cookie'), $newHeaders['vary']);
$this->assertEquals('Mon, 09 Sep 2013 00:00:00 GMT', $newHeaders['last-modified'][0]);
}

public function testOverwriteHeaders()
{
$event = $this->buildEvent();
$headers = array(
'overwrite' => true,
'cache_control' => array(
'max_age' => '900',
's_maxage' => '300',
'public' => true,
'private' => false,
'must_revalidate' => true,
'proxy_revalidate' => true,
'no_transform' => true,
'stale_if_error' => '300',
'stale_while_revalidate' => '400',
),
'vary' => array(
'Cookie',
),
'last_modified' => '2014-10-10 GMT',
);
$subscriber = $this->getCacheControl($headers);
$response = $event->getResponse();
$response->setPublic();
$response->setCache(array('max_age' => 0));
$response->headers->addCacheControlDirective('stale-if-error', 0);
$response->setVary('Encoding');
$response->setLastModified(new \DateTime('2013-09-09 GMT'));

$subscriber->onKernelResponse($event);
$newHeaders = $event->getResponse()->headers->all();

$this->assertEquals('max-age=900, must-revalidate, no-transform, proxy-revalidate, public, s-maxage=300, stale-if-error=300, stale-while-revalidate=400', $newHeaders['cache-control'][0]);
$this->assertEquals(array('Cookie'), $newHeaders['vary']);
$this->assertEquals('Fri, 10 Oct 2014 00:00:00 GMT', $newHeaders['last-modified'][0]);
}

public function testMergePublicPrivate()
{
$event = $this->buildEvent();
$headers = array(
'overwrite' => false,
'overwrite' => false,
'cache_control' => array(
'private' => true,
));
Expand All @@ -157,7 +206,7 @@ public function testSetOnlyNoCacheHeader()
{
$event = $this->buildEvent();
$headers = array(
'overwrite' => false,
'overwrite' => false,
'cache_control' => array(
'no_cache' => true,
),
Expand Down Expand Up @@ -191,11 +240,14 @@ public function testSkip()
public function testVary()
{
$event = $this->buildEvent();
$headers = array('vary' => array(
'Cookie',
'Accept-Language',
'Encoding',
));
$headers = array(
'overwrite' => false,
'vary' => array(
'Cookie',
'Accept-Language',
'Encoding',
)
);
$subscriber = $this->getCacheControl($headers);

$subscriber->onKernelResponse($event);
Expand Down
5 changes: 5 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,10 @@
"psr-4": {
"FOS\\HttpCacheBundle\\": ""
}
},
"extra": {
"branch-alias": {
"dev-master": "1.1.x-dev"
}
}
}

0 comments on commit 233420c

Please sign in to comment.