Completed
Push — master ( e59c94...9a952c )
by David
03:59
created

Varnish::getDefaultOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
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\Exception\MissingHostException;
16
use FOS\HttpCache\ProxyClient\Invalidation\BanInterface;
17
use FOS\HttpCache\ProxyClient\Invalidation\PurgeInterface;
18
use FOS\HttpCache\ProxyClient\Invalidation\RefreshInterface;
19
use FOS\HttpCache\ProxyClient\Invalidation\TagsInterface;
20
use Http\Message\MessageFactory;
21
22
/**
23
 * Varnish HTTP cache invalidator.
24
 *
25
 * Additional constructor options:
26
 * - tags_header   Header for tagging responses, defaults to X-Cache-Tags
27
 * - header_length Maximum header length, defaults to 7500 bytes
28
 *
29
 * @author David de Boer <[email protected]>
30
 */
31
class Varnish extends AbstractProxyClient 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
40
    /**
41
     * Map of default headers for ban requests with their default values.
42
     *
43
     * @var array
44
     */
45
    private $defaultBanHeaders = [
46
        self::HTTP_HEADER_HOST         => self::REGEX_MATCH_ALL,
47
        self::HTTP_HEADER_URL          => self::REGEX_MATCH_ALL,
48
        self::HTTP_HEADER_CONTENT_TYPE => self::REGEX_MATCH_ALL
49
    ];
50
51
    /**
52
     * Set the default headers that get merged with the provided headers in self::ban().
53
     *
54
     * @param array $headers Hashmap with keys being the header names, values
55
     *                       the header values.
56
     */
57 2
    public function setDefaultBanHeaders(array $headers)
58
    {
59 2
        $this->defaultBanHeaders = $headers;
60 2
    }
61
62
    /**
63
     * Add or overwrite a default ban header.
64
     *
65
     * @param string $name  The name of that header
66
     * @param string $value The content of that header
67
     */
68 2
    public function setDefaultBanHeader($name, $value)
69
    {
70 2
        $this->defaultBanHeaders[$name] = $value;
71 2
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76 4
    public function invalidateTags(array $tags)
77
    {
78 4
        $escapedTags = array_map('preg_quote', $this->escapeTags($tags));
79
80 4
        if (mb_strlen(implode('|', $escapedTags)) >= $this->options['header_length']) {
81
            /*
82
             * estimate the amount of tags to invalidate by dividing the max
83
             * header length by the largest tag (minus 1 for the implode character)
84
             */
85 1
            $tagsize = max(array_map('mb_strlen', $escapedTags));
86 1
            $elems = floor($this->options['header_length'] / ($tagsize - 1)) ? : 1;
87 1
        } else {
88 3
            $elems = count($escapedTags);
89
        }
90
91 4
        foreach (array_chunk($escapedTags, $elems) as $tagchunk) {
92 4
            $tagExpression = sprintf('(%s)(,.+)?$', implode('|', $tagchunk));
93 4
            $this->ban([$this->options['tags_header'] => $tagExpression]);
94 4
        }
95
96 4
        return $this;
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function getTagsHeaderValue(array $tags)
103
    {
104
        return array_unique($this->escapeTags($tags));
105
    }
106
107
    /**
108
     * Get the HTTP header name that will hold cache tags.
109
     *
110
     * @return string
111
     */
112 1
    public function getTagsHeaderName()
113
    {
114 1
        return $this->options['tags_header'];
115
    }
116
117
    /**
118
     * Get the maximum HTTP header length.
119
     *
120
     * @return int
121
     */
122 1
    public function getHeaderLength()
123
    {
124 1
        return $this->options['header_length'];
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130 12
    public function ban(array $headers)
131
    {
132 12
        $headers = array_merge(
133 12
            $this->defaultBanHeaders,
134
            $headers
135 12
        );
136
137 12
        $this->queueRequest(self::HTTP_METHOD_BAN, '/', $headers);
138
139 12
        return $this;
140
    }
141
142
    /**
143
     * {@inheritdoc}
144
     */
145 4
    public function banPath($path, $contentType = null, $hosts = null)
146
    {
147 4
        if (is_array($hosts)) {
148 2
            if (!count($hosts)) {
149 1
                throw new InvalidArgumentException('Either supply a list of hosts or null, but not an empty array.');
150
            }
151 1
            $hosts = '^('.join('|', $hosts).')$';
152 1
        }
153
154
        $headers = [
155 3
            self::HTTP_HEADER_URL => $path,
156 3
        ];
157
158 3
        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...
159 2
            $headers[self::HTTP_HEADER_CONTENT_TYPE] = $contentType;
160 2
        }
161 3
        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...
162 1
            $headers[self::HTTP_HEADER_HOST] = $hosts;
163 1
        }
164
165 3
        return $this->ban($headers);
166
    }
167
168
    /**
169
     * {@inheritdoc}
170
     */
171 11
    public function purge($url, array $headers = [])
172
    {
173 11
        $this->queueRequest(self::HTTP_METHOD_PURGE, $url, $headers);
174
175 10
        return $this;
176
    }
177
178
    /**
179
     * {@inheritdoc}
180
     */
181 3 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...
182
    {
183 3
        $headers = array_merge($headers, ['Cache-Control' => 'no-cache']);
184 3
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
185
186 3
        return $this;
187
    }
188
189
    /**
190
     * {@inheritdoc}
191
     */
192 35
    protected function getDefaultOptions()
193
    {
194 35
        $resolver = parent::getDefaultOptions();
195 35
        $resolver->setDefaults(['tags_header' => 'X-Cache-Tags']);
196 35
        $resolver->setDefaults(['header_length' => 7500]);
197
198 35
        return $resolver;
199
    }
200
201
    /**
202
     * Build the invalidation request and validate it.
203
     *
204
     * {@inheritdoc}
205
     *
206
     * @throws MissingHostException If a relative path is queued for purge/
207
     *                              refresh and no base URL is set
208
     *
209
     */
210 26
    protected function queueRequest($method, $url, array $headers = [])
211
    {
212 26
        $request = $this->messageFactory->createRequest($method, $url, $headers);
213
214 26
        if (self::HTTP_METHOD_BAN !== $method
215 26
            && null === $this->options['base_uri']
216 26
            && !$request->getHeaderLine('Host')
217 26
        ) {
218 1
            throw MissingHostException::missingHost($url);
219
        }
220
221 25
        $this->httpAdapter->invalidate($request);
222 25
    }
223
}
224