Completed
Pull Request — master (#257)
by David de
05:25
created

Varnish   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 198
Duplicated Lines 3.54 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 93.33%

Importance

Changes 8
Bugs 1 Features 2
Metric Value
wmc 19
c 8
b 1
f 2
lcom 1
cbo 7
dl 7
loc 198
ccs 56
cts 60
cp 0.9333
rs 10

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A setDefaultBanHeaders() 0 4 1
A setDefaultBanHeader() 0 4 1
A invalidateTags() 0 6 1
A getTagsHeaderValue() 0 4 1
A getTagsHeaderName() 0 4 1
A ban() 0 11 1
B banPath() 0 22 5
A purge() 0 6 1
A refresh() 7 7 1
A getDefaultOptions() 0 7 1
A queueRequest() 0 13 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
    /**
57
     * @var string
58
     */
59
    private $tagsHeader;
60
61
    /**
62
     * {@inheritdoc}
63
     *
64
     * Additional options:
65
     *
66
     * - tags_header Header for tagging responses, defaults to X-Cache-Tags
67
     *
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
     */
70 32
    public function __construct(
71
        array $servers,
72
        array $options = [],
73 1
        HttpAsyncClient $httpClient = null,
74
        MessageFactory $messageFactory = null
75
    ) {
76 32
        parent::__construct($servers, $options, $httpClient, $messageFactory);
77 29
        $this->baseUriSet = $this->options['base_uri'] !== null;
78 29
        $this->tagsHeader = $this->options['tags_header'];
79 29
    }
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 2
    public function setDefaultBanHeaders(array $headers)
88
    {
89 2
        $this->defaultBanHeaders = $headers;
90 2
    }
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 2
    public function setDefaultBanHeader($name, $value)
99
    {
100 2
        $this->defaultBanHeaders[$name] = $value;
101 2
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106 3
    public function invalidateTags(array $tags)
107
    {
108 3
        $tagExpression = sprintf('(%s)(,.+)?$', implode('|', array_map('preg_quote', $this->escapeTags($tags))));
109
110 3
        return $this->ban([$this->tagsHeader => $tagExpression]);
111
    }
112
113
    /**
114
     * {@inheritdoc}
115
     */
116
    public function getTagsHeaderValue(array $tags)
117
    {
118
        return implode(',', array_unique($this->escapeTags($tags)));
119
    }
120
121
    /**
122
     * Get the HTTP header name that will hold cache tags.
123
     *
124
     * @return string
125
     */
126
    public function getTagsHeaderName()
127
    {
128
        return $this->tagsHeader;
129
    }
130
131
    /**
132
     * {@inheritdoc}
133
     */
134 11
    public function ban(array $headers)
135
    {
136 11
        $headers = array_merge(
137 11
            $this->defaultBanHeaders,
138
            $headers
139 11
        );
140
141 11
        $this->queueRequest(self::HTTP_METHOD_BAN, '/', $headers);
142
143 11
        return $this;
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149 4
    public function banPath($path, $contentType = null, $hosts = null)
150
    {
151 4
        if (is_array($hosts)) {
152 2
            if (!count($hosts)) {
153 1
                throw new InvalidArgumentException('Either supply a list of hosts or null, but not an empty array.');
154
            }
155 1
            $hosts = '^('.join('|', $hosts).')$';
156 1
        }
157
158
        $headers = [
159 3
            self::HTTP_HEADER_URL => $path,
160 3
        ];
161
162 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...
163 2
            $headers[self::HTTP_HEADER_CONTENT_TYPE] = $contentType;
164 2
        }
165 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...
166 1
            $headers[self::HTTP_HEADER_HOST] = $hosts;
167 1
        }
168
169 3
        return $this->ban($headers);
170
    }
171
172
    /**
173
     * {@inheritdoc}
174
     */
175 11
    public function purge($url, array $headers = [])
176
    {
177 11
        $this->queueRequest(self::HTTP_METHOD_PURGE, $url, $headers);
178
179 10
        return $this;
180
    }
181
182
    /**
183
     * {@inheritdoc}
184
     */
185 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...
186
    {
187 3
        $headers = array_merge($headers, ['Cache-Control' => 'no-cache']);
188 3
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
189
190 3
        return $this;
191
    }
192
193
    /**
194
     * {@inheritdoc}
195
     */
196 32
    protected function getDefaultOptions()
197
    {
198 32
        $resolver = parent::getDefaultOptions();
199 32
        $resolver->setDefault('tags_header', 'X-Cache-Tags');
200
201 32
        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 25
    protected function queueRequest($method, $url, array $headers = [])
214
    {
215 25
        $request = $this->messageFactory->createRequest($method, $url, $headers);
216
217 25
        if (self::HTTP_METHOD_BAN !== $method
218 25
            && !$this->baseUriSet
219 25
            && !$request->getHeaderLine('Host')
220 25
        ) {
221 1
            throw MissingHostException::missingHost($url);
222
        }
223
224 24
        $this->httpAdapter->invalidate($request);
225 24
    }
226
}
227