Completed
Pull Request — master (#272)
by David
85:16 queued 73:52
created

Varnish::refresh()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 7
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 7
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
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
 *
28
 * @author David de Boer <[email protected]>
29
 */
30
class Varnish extends AbstractProxyClient implements BanInterface, PurgeInterface, RefreshInterface, TagsInterface
31
{
32
    const HTTP_METHOD_BAN          = 'BAN';
33
    const HTTP_METHOD_PURGE        = 'PURGE';
34
    const HTTP_METHOD_REFRESH      = 'GET';
35
    const HTTP_HEADER_HOST         = 'X-Host';
36
    const HTTP_HEADER_URL          = 'X-Url';
37
    const HTTP_HEADER_CONTENT_TYPE = 'X-Content-Type';
38
39
    /**
40
     * Map of default headers for ban requests with their default values.
41
     *
42
     * @var array
43
     */
44
    private $defaultBanHeaders = [
45
        self::HTTP_HEADER_HOST         => self::REGEX_MATCH_ALL,
46
        self::HTTP_HEADER_URL          => self::REGEX_MATCH_ALL,
47
        self::HTTP_HEADER_CONTENT_TYPE => self::REGEX_MATCH_ALL
48
    ];
49
50
    /**
51
     * Set the default headers that get merged with the provided headers in self::ban().
52
     *
53
     * @param array $headers Hashmap with keys being the header names, values
54
     *                       the header values.
55
     */
56
    public function setDefaultBanHeaders(array $headers)
57
    {
58
        $this->defaultBanHeaders = $headers;
59
    }
60
61
    /**
62
     * Add or overwrite a default ban header.
63
     *
64
     * @param string $name  The name of that header
65
     * @param string $value The content of that header
66
     */
67
    public function setDefaultBanHeader($name, $value)
68
    {
69
        $this->defaultBanHeaders[$name] = $value;
70 32
    }
71
72
    /**
73 1
     * {@inheritdoc}
74
     */
75
    public function invalidateTags(array $tags)
76 32
    {
77 29
        $tagExpression = sprintf('(%s)(,.+)?$', implode('|', array_map('preg_quote', $this->escapeTags($tags))));
78 29
79 29
        return $this->ban([$this->options['tags_header'] => $tagExpression]);
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function getTagsHeaderValue(array $tags)
86
    {
87 2
        return implode(',', array_unique($this->escapeTags($tags)));
88
    }
89 2
90 2
    /**
91
     * Get the HTTP header name that will hold cache tags.
92
     *
93
     * @return string
94
     */
95
    public function getTagsHeaderName()
96
    {
97
        return $this->options['tags_header'];
98 2
    }
99
100 2
    /**
101 2
     * {@inheritdoc}
102
     */
103
    public function ban(array $headers)
104
    {
105
        $headers = array_merge(
106 3
            $this->defaultBanHeaders,
107
            $headers
108 3
        );
109
110 3
        $this->queueRequest(self::HTTP_METHOD_BAN, '/', $headers);
111
112
        return $this;
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118
    public function banPath($path, $contentType = null, $hosts = null)
119
    {
120
        if (is_array($hosts)) {
121
            if (!count($hosts)) {
122
                throw new InvalidArgumentException('Either supply a list of hosts or null, but not an empty array.');
123
            }
124
            $hosts = '^('.join('|', $hosts).')$';
125
        }
126
127
        $headers = [
128
            self::HTTP_HEADER_URL => $path,
129
        ];
130
131
        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...
132
            $headers[self::HTTP_HEADER_CONTENT_TYPE] = $contentType;
133
        }
134 11
        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...
135
            $headers[self::HTTP_HEADER_HOST] = $hosts;
136 11
        }
137 11
138
        return $this->ban($headers);
139 11
    }
140
141 11
    /**
142
     * {@inheritdoc}
143 11
     */
144
    public function purge($url, array $headers = [])
145
    {
146
        $this->queueRequest(self::HTTP_METHOD_PURGE, $url, $headers);
147
148
        return $this;
149 4
    }
150
151 4
    /**
152 2
     * {@inheritdoc}
153 1
     */
154 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...
155 1
    {
156 1
        $headers = array_merge($headers, ['Cache-Control' => 'no-cache']);
157
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
158
159 3
        return $this;
160 3
    }
161
162 3
    /**
163 2
     * {@inheritdoc}
164 2
     */
165 3
    protected function getDefaultOptions()
166 1
    {
167 1
        $resolver = parent::getDefaultOptions();
168
        $resolver->setDefaults(['tags_header' => 'X-Cache-Tags']);
169 3
170
        return $resolver;
171
    }
172
173
    /**
174
     * Build the invalidation request and validate it.
175 11
     *
176
     * {@inheritdoc}
177 11
     *
178
     * @throws MissingHostException If a relative path is queued for purge/
179 10
     *                              refresh and no base URL is set
180
     *
181
     */
182
    protected function queueRequest($method, $url, array $headers = [])
183
    {
184
        $request = $this->messageFactory->createRequest($method, $url, $headers);
185 3
186
        if (self::HTTP_METHOD_BAN !== $method
187 3
            && null === $this->options['base_uri']
188 3
            && !$request->getHeaderLine('Host')
189
        ) {
190 3
            throw MissingHostException::missingHost($url);
191
        }
192
193
        $this->httpAdapter->invalidate($request);
194
    }
195
}
196