Completed
Pull Request — master (#272)
by David
75:19 queued 38:04
created

Varnish::ban()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 11
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 6
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\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
use Http\Message\UriFactory;
22
23
/**
24
 * Varnish HTTP cache invalidator.
25
 *
26
 * Additional constructor options:
27
 * - tags_header Header for tagging responses, defaults to X-Cache-Tags
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
    public function setDefaultBanHeaders(array $headers)
58
    {
59
        $this->defaultBanHeaders = $headers;
60
    }
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
    public function setDefaultBanHeader($name, $value)
69
    {
70 32
        $this->defaultBanHeaders[$name] = $value;
71
    }
72
73 1
    /**
74
     * {@inheritdoc}
75
     */
76 32
    public function invalidateTags(array $tags)
77 29
    {
78 29
        $tagExpression = sprintf('(%s)(,.+)?$', implode('|', array_map('preg_quote', $this->escapeTags($tags))));
79 29
80
        return $this->ban([$this->options['tags_header'] => $tagExpression]);
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86
    public function getTagsHeaderValue(array $tags)
87 2
    {
88
        return implode(',', array_unique($this->escapeTags($tags)));
89 2
    }
90 2
91
    /**
92
     * Get the HTTP header name that will hold cache tags.
93
     *
94
     * @return string
95
     */
96
    public function getTagsHeaderName()
97
    {
98 2
        return $this->options['tags_header'];
99
    }
100 2
101 2
    /**
102
     * {@inheritdoc}
103
     */
104
    public function ban(array $headers)
105
    {
106 3
        $headers = array_merge(
107
            $this->defaultBanHeaders,
108 3
            $headers
109
        );
110 3
111
        $this->queueRequest(self::HTTP_METHOD_BAN, '/', $headers);
112
113
        return $this;
114
    }
115
116
    /**
117
     * {@inheritdoc}
118
     */
119
    public function banPath($path, $contentType = null, $hosts = null)
120
    {
121
        if (is_array($hosts)) {
122
            if (!count($hosts)) {
123
                throw new InvalidArgumentException('Either supply a list of hosts or null, but not an empty array.');
124
            }
125
            $hosts = '^('.join('|', $hosts).')$';
126
        }
127
128
        $headers = [
129
            self::HTTP_HEADER_URL => $path,
130
        ];
131
132
        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...
133
            $headers[self::HTTP_HEADER_CONTENT_TYPE] = $contentType;
134 11
        }
135
        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...
136 11
            $headers[self::HTTP_HEADER_HOST] = $hosts;
137 11
        }
138
139 11
        return $this->ban($headers);
140
    }
141 11
142
    /**
143 11
     * {@inheritdoc}
144
     */
145
    public function purge($url, array $headers = [])
146
    {
147
        $this->queueRequest(self::HTTP_METHOD_PURGE, $url, $headers);
148
149 4
        return $this;
150
    }
151 4
152 2
    /**
153 1
     * {@inheritdoc}
154
     */
155 1 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...
156 1
    {
157
        $headers = array_merge($headers, ['Cache-Control' => 'no-cache']);
158
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
159 3
160 3
        return $this;
161
    }
162 3
163 2
    /**
164 2
     * {@inheritdoc}
165 3
     */
166 1
    protected function getDefaultOptions()
167 1
    {
168
        $resolver = parent::getDefaultOptions();
169 3
        $resolver->setDefaults(['tags_header' => 'X-Cache-Tags']);
170
171
        return $resolver;
172
    }
173
174
    /**
175 11
     * Build the invalidation request and validate it.
176
     *
177 11
     * {@inheritdoc}
178
     *
179 10
     * @throws MissingHostException If a relative path is queued for purge/
180
     *                              refresh and no base URL is set
181
     *
182
     */
183
    protected function queueRequest($method, $url, array $headers = [])
184
    {
185 3
        $request = $this->messageFactory->createRequest($method, $url, $headers);
186
187 3
        if (self::HTTP_METHOD_BAN !== $method
188 3
            && null === $this->options['base_uri']
189
            && !$request->getHeaderLine('Host')
190 3
        ) {
191
            throw MissingHostException::missingHost($url);
192
        }
193
194
        $this->httpAdapter->invalidate($request);
195
    }
196
}
197