Completed
Pull Request — master (#271)
by
unknown
13:29
created

Varnish::getDefaultOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 0
cts 0
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
crap 2
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\Client\HttpAsyncClient;
21
use Http\Message\MessageFactory;
22
use Symfony\Component\OptionsResolver\OptionsResolver;
23
24
/**
25
 * Varnish HTTP cache invalidator.
26
 *
27
 * @author David de Boer <[email protected]>
28
 */
29
class Varnish extends AbstractProxyClient implements BanInterface, PurgeInterface, RefreshInterface, TagsInterface
30
{
31
    const HTTP_METHOD_BAN          = 'BAN';
32
    const HTTP_METHOD_PURGE        = 'PURGE';
33
    const HTTP_METHOD_REFRESH      = 'GET';
34
    const HTTP_HEADER_HOST         = 'X-Host';
35
    const HTTP_HEADER_URL          = 'X-Url';
36
    const HTTP_HEADER_CONTENT_TYPE = 'X-Content-Type';
37
38
    /**
39
     * Map of default headers for ban requests with their default values.
40
     *
41
     * @var array
42
     */
43
    private $defaultBanHeaders = [
44
        self::HTTP_HEADER_HOST         => self::REGEX_MATCH_ALL,
45
        self::HTTP_HEADER_URL          => self::REGEX_MATCH_ALL,
46
        self::HTTP_HEADER_CONTENT_TYPE => self::REGEX_MATCH_ALL
47
    ];
48
49
    /**
50
     * Has a base URI been set?
51
     *
52
     * @var bool
53
     */
54
    private $baseUriSet;
55
56 2
    /**
57
     * @var string
58 2
     */
59 2
    private $tagsHeader;
60
61
    /**
62
     * {@inheritdoc}
63
     *
64
     * Additional options:
65
     *
66
     * - tags_header Header for tagging responses, defaults to X-Cache-Tags
67 2
     *
68
     * @param string $tagsHeader
0 ignored issues
show
Bug introduced by
There is no parameter named $tagsHeader. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
69 2
     */
70 2
    public function __construct(
71
        array $servers,
72
        array $options = [],
73
        HttpAsyncClient $httpClient = null,
74
        MessageFactory $messageFactory = null
75 3
    ) {
76
        parent::__construct($servers, $options, $httpClient, $messageFactory);
77 3
        $this->baseUriSet = $this->options['base_uri'] !== null;
78
        $this->tagsHeader = $this->options['tags_header'];
79 3
    }
80
81
    /**
82
     * Set the default headers that get merged with the provided headers in self::ban().
83
     *
84
     * @param array $headers Hashmap with keys being the header names, values
85
     *                       the header values.
86
     */
87
    public function setDefaultBanHeaders(array $headers)
88
    {
89
        $this->defaultBanHeaders = $headers;
90
    }
91
92
    /**
93
     * Add or overwrite a default ban header.
94
     *
95
     * @param string $name  The name of that header
96
     * @param string $value The content of that header
97
     */
98
    public function setDefaultBanHeader($name, $value)
99
    {
100
        $this->defaultBanHeaders[$name] = $value;
101
    }
102
103 11
    /**
104
     * {@inheritdoc}
105 11
     */
106 11
    public function invalidateTags(array $tags)
107
    {
108 11
        $tagExpression = sprintf('(%s)(,.+)?$', implode('|', array_map('preg_quote', $this->escapeTags($tags))));
109
110 11
        return $this->ban([$this->tagsHeader => $tagExpression]);
111
    }
112 11
113
    /**
114
     * {@inheritdoc}
115
     */
116
    public function getTagsHeaderValue(array $tags)
117
    {
118 4
        return implode(',', array_unique($this->escapeTags($tags)));
119
    }
120 4
121 2
    /**
122 1
     * Get the HTTP header name that will hold cache tags.
123
     *
124 1
     * @return string
125 1
     */
126
    public function getTagsHeaderName()
127
    {
128 3
        return $this->tagsHeader;
129 3
    }
130
131 3
    /**
132 2
     * {@inheritdoc}
133 2
     */
134 3
    public function ban(array $headers)
135 1
    {
136 1
        $headers = array_merge(
137
            $this->defaultBanHeaders,
138 3
            $headers
139
        );
140
141
        $this->queueRequest(self::HTTP_METHOD_BAN, '/', $headers);
142
143
        return $this;
144 11
    }
145
146 11
    /**
147
     * {@inheritdoc}
148 10
     */
149
    public function banPath($path, $contentType = null, $hosts = null)
150
    {
151
        if (is_array($hosts)) {
152
            if (!count($hosts)) {
153
                throw new InvalidArgumentException('Either supply a list of hosts or null, but not an empty array.');
154 3
            }
155
            $hosts = '^('.join('|', $hosts).')$';
156 3
        }
157 3
158
        $headers = [
159 3
            self::HTTP_HEADER_URL => $path,
160
        ];
161
162
        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...
163
            $headers[self::HTTP_HEADER_CONTENT_TYPE] = $contentType;
164
        }
165 32
        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...
166
            $headers[self::HTTP_HEADER_HOST] = $hosts;
167 32
        }
168 32
169
        return $this->ban($headers);
170 32
    }
171
172
    /**
173
     * {@inheritdoc}
174
     */
175
    public function purge($url, array $headers = [])
176
    {
177
        $this->queueRequest(self::HTTP_METHOD_PURGE, $url, $headers);
178
179
        return $this;
180
    }
181
182 25
    /**
183
     * {@inheritdoc}
184 25
     */
185 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...
186 25
    {
187 25
        $headers = array_merge($headers, ['Cache-Control' => 'no-cache']);
188 25
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
189 25
190 1
        return $this;
191
    }
192
193 24
    /**
194 24
     * {@inheritdoc}
195
     */
196
    protected function getDefaultOptions()
197
    {
198
        $resolver = parent::getDefaultOptions();
199
        $resolver->setDefaults(['tags_header' => 'X-Cache-Tags']);
200
201
        return $resolver;
202
    }
203
204
    /**
205
     * Build the invalidation request and validate it.
206
     *
207
     * {@inheritdoc}
208
     *
209
     * @throws MissingHostException If a relative path is queued for purge/
210
     *                              refresh and no base URL is set
211
     *
212
     */
213
    protected function queueRequest($method, $url, array $headers = [])
214
    {
215
        $request = $this->messageFactory->createRequest($method, $url, $headers);
216
217
        if (self::HTTP_METHOD_BAN !== $method
218
            && !$this->baseUriSet
219
            && !$request->getHeaderLine('Host')
220
        ) {
221
            throw MissingHostException::missingHost($url);
222
        }
223
224
        $this->httpAdapter->invalidate($request);
225
    }
226
}
227