Skip to content

Allow override of request cache headers #151

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 21, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,15 @@ private function addCacheControlSection(ArrayNodeDefinition $rootNode)
->arrayNode('cache_control')
->fixXmlConfig('rule')
->children()
->arrayNode('defaults')
->addDefaultsIfNotSet()
->children()
->booleanNode('overwrite')
->info('Whether to overwrite existing cache headers')
->defaultFalse()
->end()
->end()
->end()
->arrayNode('rules')
->prototype('array')
->children();
Expand All @@ -158,6 +167,11 @@ private function addCacheControlSection(ArrayNodeDefinition $rootNode)
->isRequired()
// todo validate there is some header defined
->children()
->enumNode('overwrite')
->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()
->arrayNode('cache_control')
->info('Add the specified cache control directives.')
->children()
Expand Down
8 changes: 6 additions & 2 deletions DependencyInjection/FOSHttpCacheExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,12 @@ private function loadCacheControl(ContainerBuilder $container, array $config)

foreach ($config['rules'] as $rule) {
$ruleMatcher = $this->parseRuleMatcher($container, $rule['match']);
$controlDefinition->addMethodCall('addRule', array($ruleMatcher, $rule['headers']))
;

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

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

Expand Down
33 changes: 25 additions & 8 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);
$this->setCache($response, $directives, $options['overwrite']);
}
if (!empty($extraDirectives)) {
$this->setExtraCacheDirectives($response, $extraDirectives);
$this->setExtraCacheDirectives($response, $extraDirectives, $options['overwrite']);
}
}

Expand All @@ -127,17 +127,32 @@ 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']);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gonzalovilaseca i propose that we use the overwrite flag with all headers, not only cache directives but also vary and last-modified (below). otherwise it would need a more specific name. but i think this is the expected - i want to overwrite the things i configure.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ddeboer btw, no idea why this was previously that complicated - the symfony HeaderBag already does the merge if the second argument is false ("$replace").

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dbu it makes total sense to overwrite both.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dbu Lol, good one. :)

}

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']));
}
}
}

private function setCache(Response $response, array $directives)
/**
* Set cache headers on response.
*
* @param Response $response
* @param array $directives
* @param boolean $overwrite Whether to keep existing cache headers or to overwrite them.
*/
private function setCache(Response $response, array $directives, $overwrite)
{
if ($overwrite) {
$response->setCache($directives);

return;
}

if ('no-cache' === $response->headers->get('cache-control')) {
// this single header is set by default. if its the only thing, we override it.
$response->setCache($directives);
Expand Down Expand Up @@ -165,16 +180,17 @@ private function setCache(Response $response, array $directives)
*
* @param Response $response
* @param array $controls
* @param boolean $overwrite Whether to keep existing cache headers or to overwrite them.
*/
private function setExtraCacheDirectives(Response $response, array $controls)
private function setExtraCacheDirectives(Response $response, array $controls, $overwrite)
{
$flags = array('must_revalidate', 'proxy_revalidate', 'no_transform', 'no_cache');
$options = array('stale_if_error', 'stale_while_revalidate');

foreach ($flags as $key) {
$flag = str_replace('_', '-', $key);
if (!empty($controls[$key])
&& !$response->headers->hasCacheControlDirective($flag)
&& ($overwrite || !$response->headers->hasCacheControlDirective($flag))
) {
$response->headers->addCacheControlDirective($flag);
}
Expand All @@ -183,9 +199,10 @@ private function setExtraCacheDirectives(Response $response, array $controls)
foreach ($options as $key) {
$option = str_replace('_', '-', $key);
if (isset($controls[$key])
&& !$response->headers->hasCacheControlDirective($option)
&& ($overwrite || !$response->headers->hasCacheControlDirective($option))
) {
$response->headers->addCacheControlDirective($option, $controls[$key]);

}
}
}
Expand Down
11 changes: 10 additions & 1 deletion Resources/doc/features/headers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,21 @@ 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.

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:

.. code-block:: yaml

# app/config/config.yml
fos_http_cache:
cache_control:
defaults:
overwrite: true
rules:
# only match login.example.com
-
Expand Down Expand Up @@ -48,8 +56,9 @@ For instance:
# match everything to set defaults
-
match:
path: ^/
path: ^/
headers:
overwrite: false
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ddeboer i am not really happy that this configuration is at the same place as the headers configuration. but i don't see where else we can put it without changing a lot in the data structure.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It”s okay with me.

If we could change the data structure, what would you propose?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if i knew, i would already have proposed something :-)
lets leave it at this. i will wait with merging until #128 is through,
then tag and create the 1.0 branch so we can start with this as 1.1 version

cache_control: { public: true, max_age: 15, s_maxage: 30 }
last_modified: "-1 hour"

Expand Down
6 changes: 6 additions & 0 deletions Resources/doc/reference/configuration/headers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,23 @@ 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 ``overwrite`` option allow to overwrite the
cache headers even if they are already set.

.. code-block:: yaml

# app/config/config.yml
fos_http_cache:
cache_control:
defaults:
overwrite: false
rules:
# only match login.example.com
-
match:
host: ^login.example.com$
headers:
overwrite: true
cache_control:
public: false
max_age: 0
Expand Down
4 changes: 4 additions & 0 deletions Tests/Resources/Fixtures/config/full.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

$container->loadFromExtension('fos_http_cache', array(
'cache_control' => array(
'defaults' => array(
'overwrite' => true
),
'rules' => array(
array(
'match' => array(
Expand All @@ -13,6 +16,7 @@
'additional_cacheable_status' => array(100, 500),
),
'headers' => array(
'overwrite' => false,
'cache_control' => array(
'max_age' => 1,
's_maxage' => 2,
Expand Down
4 changes: 4 additions & 0 deletions Tests/Resources/Fixtures/config/full.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@

<config xmlns="http://example.org/schema/dic/fos_http_cache">
<cache-control>
<defaults>
<overwrite>true</overwrite>
</defaults>
<rule>
<match
path="/abc"
Expand All @@ -17,6 +20,7 @@
<additional-cacheable-status>500</additional-cacheable-status>
</match>
<headers last-modified="-1 hour" reverse-proxy-ttl="42">
<overwrite>false</overwrite>
<cache-control
max-age="1"
s-maxage="2"
Expand Down
3 changes: 3 additions & 0 deletions Tests/Resources/Fixtures/config/full.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
fos_http_cache:

cache_control:
defaults:
overwrite: true
rules:
-
match:
Expand All @@ -18,6 +20,7 @@ fos_http_cache:
- 100
- 500
headers:
overwrite: false
cache_control:
max_age: 1
s_maxage: 2
Expand Down
8 changes: 8 additions & 0 deletions Tests/Unit/DependencyInjection/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ public function testSupportsAllConfigFormats()
{
$expectedConfiguration = array(
'cache_control' => array(
'defaults' => array(
'overwrite' => true,
),
'rules' => array(
array(
'match' => array(
Expand All @@ -62,6 +65,7 @@ public function testSupportsAllConfigFormats()
// TODO 'match_response' => '',
),
'headers' => array(
'overwrite' => false,
'cache_control' => array(
'max_age' => 1,
's_maxage' => 2,
Expand Down Expand Up @@ -220,9 +224,13 @@ public function testSplitOptions()
'headers' => array(
'reverse_proxy_ttl' => null,
'vary' => array('Cookie', 'Authorization'),
'overwrite' => 'default',
),
),
),
'defaults' => array(
'overwrite' => false,
),
);
$expectedConfiguration['proxy_client'] = array(
'varnish' => array(
Expand Down
Loading