Completed
Pull Request — master (#312)
by David
12:51 queued 09:06
created

Varnish::setDefaultBanHeaders()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
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 FOSHttpCache 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\HttpCache\ProxyClient;
13
14
use FOS\HttpCache\Exception\InvalidArgumentException;
15
use FOS\HttpCache\ProxyClient\Invalidation\BanInterface;
16
use FOS\HttpCache\ProxyClient\Invalidation\PurgeInterface;
17
use FOS\HttpCache\ProxyClient\Invalidation\RefreshInterface;
18
use FOS\HttpCache\ProxyClient\Invalidation\TagsInterface;
19
20
/**
21
 * Varnish HTTP cache invalidator.
22
 *
23
 * Additional constructor options:
24
 * - tags_header         Header for tagging responses, defaults to X-Cache-Tags
25
 * - header_length       Maximum header length, defaults to 7500 bytes
26
 * - default_ban_headers Map of headers that are set on each ban request,
27
 *                       merged with the built-in headers
28
 *
29
 * @author David de Boer <[email protected]>
30
 */
31
class Varnish extends HttpProxyClient implements BanInterface, PurgeInterface, RefreshInterface, TagsInterface
32
{
33
    const HTTP_METHOD_BAN = 'BAN';
34
    const HTTP_METHOD_PURGE = 'PURGE';
35
    const HTTP_METHOD_REFRESH = 'GET';
36
    const HTTP_HEADER_HOST = 'X-Host';
37
    const HTTP_HEADER_URL = 'X-Url';
38
    const HTTP_HEADER_CONTENT_TYPE = 'X-Content-Type';
39
    const DEFAULT_HTTP_HEADER_CACHE_TAGS = 'X-Cache-Tags';
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 1
    public function invalidateTags(array $tags)
45
    {
46 1
        $escapedTags = array_map('preg_quote', $this->escapeTags($tags));
47
48 1
        if (mb_strlen(implode('|', $escapedTags)) >= $this->options['header_length']) {
49
            /*
50
             * estimate the amount of tags to invalidate by dividing the max
51
             * header length by the largest tag (minus 1 for the implode character)
52
             */
53
            $tagsize = max(array_map('mb_strlen', $escapedTags));
54
            $elems = floor($this->options['header_length'] / ($tagsize - 1)) ?: 1;
55
        } else {
56 1
            $elems = count($escapedTags);
57
        }
58
59 1
        foreach (array_chunk($escapedTags, $elems) as $tagchunk) {
60 1
            $tagExpression = sprintf('(%s)(,.+)?$', implode('|', $tagchunk));
61 1
            $this->ban([$this->options['tags_header'] => $tagExpression]);
62 1
        }
63
64 1
        return $this;
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function getTagsHeaderValue(array $tags)
71
    {
72
        return array_unique($this->escapeTags($tags));
73
    }
74
75
    /**
76
     * Get the HTTP header name that will hold cache tags.
77
     *
78
     * @return string
79
     */
80
    public function getTagsHeaderName()
81
    {
82
        return $this->options['tags_header'];
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88 6
    public function ban(array $headers)
89
    {
90 6
        $headers = array_merge(
91 6
            $this->options['default_ban_headers'],
92
            $headers
93 6
        );
94
95 6
        $this->queueRequest(self::HTTP_METHOD_BAN, '/', $headers);
96
97 6
        return $this;
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103 2
    public function banPath($path, $contentType = null, $hosts = null)
104
    {
105 2
        if (is_array($hosts)) {
106
            if (!count($hosts)) {
107
                throw new InvalidArgumentException('Either supply a list of hosts or null, but not an empty array.');
108
            }
109
            $hosts = '^('.implode('|', $hosts).')$';
110
        }
111
112
        $headers = [
113 2
            self::HTTP_HEADER_URL => $path,
114 2
        ];
115
116 2
        if ($contentType) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $contentType of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
117 1
            $headers[self::HTTP_HEADER_CONTENT_TYPE] = $contentType;
118 1
        }
119 2
        if ($hosts) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $hosts of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
120
            $headers[self::HTTP_HEADER_HOST] = $hosts;
121
        }
122
123 2
        return $this->ban($headers);
124
    }
125
126
    /**
127
     * {@inheritdoc}
128
     */
129 3
    public function purge($url, array $headers = [])
130
    {
131 3
        $this->queueRequest(self::HTTP_METHOD_PURGE, $url, $headers);
132
133 3
        return $this;
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139 2 View Code Duplication
    public function refresh($url, array $headers = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
140
    {
141 2
        $headers = array_merge($headers, ['Cache-Control' => 'no-cache']);
142 2
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
143
144 2
        return $this;
145
    }
146
147
    /**
148
     * {@inheritdoc}
149
     */
150 13
    protected function getDefaultOptions()
151
    {
152 13
        $resolver = parent::getDefaultOptions();
153 13
        $resolver->setDefaults([
154 13
            'tags_header' => self::DEFAULT_HTTP_HEADER_CACHE_TAGS,
155 13
            'header_length' => 7500,
156 13
            'default_ban_headers' => [],
157 13
        ]);
158 13
        $resolver->setNormalizer('default_ban_headers', function ($resolver, $specified) {
159 13
            return array_merge(
160
                [
161 13
                    self::HTTP_HEADER_HOST => self::REGEX_MATCH_ALL,
162 13
                    self::HTTP_HEADER_URL => self::REGEX_MATCH_ALL,
163 13
                    self::HTTP_HEADER_CONTENT_TYPE => self::REGEX_MATCH_ALL,
164 13
                ],
165
                $specified
166 13
            );
167 13
        });
168
169 13
        return $resolver;
170
    }
171
}
172