Completed
Pull Request — master (#332)
by André
04:01 queued 02:10
created

Varnish   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 143
Duplicated Lines 4.9 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 3
dl 7
loc 143
ccs 47
cts 47
cp 1
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
B invalidateTags() 0 23 4
A ban() 0 11 1
B banPath() 0 22 5
A purge() 0 6 1
A refresh() 7 7 1
B configureOptions() 0 24 1

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\ProxyClient\Invalidation\BanCapable;
16
use FOS\HttpCache\ProxyClient\Invalidation\PurgeCapable;
17
use FOS\HttpCache\ProxyClient\Invalidation\RefreshCapable;
18
use FOS\HttpCache\ProxyClient\Invalidation\TagCapable;
19
20
/**
21
 * Varnish HTTP cache invalidator.
22
 *
23
 * Additional constructor options:
24
 * - tags_header         Header for sending tag invalidation requests to
25
 *                       Varnish, defaults to X-Cache-Tags
26
 * - header_length       Maximum header length when invalidating tags. If there
27
 *                       are more tags to invalidate than fit into the header,
28
 *                       the invalidation request is split into several requests.
29
 *                       Defaults to 7500
30
 * - default_ban_headers Map of header name => header value that have to be set
31
 *                       on each ban request, merged with the built-in headers
32
 *
33
 * @author David de Boer <[email protected]>
34
 */
35
class Varnish extends HttpProxyClient implements BanCapable, PurgeCapable, RefreshCapable, TagCapable
36
{
37
    const HTTP_METHOD_BAN = 'BAN';
38
39
    const HTTP_METHOD_PURGE = 'PURGE';
40
41
    const HTTP_METHOD_PURGEKEYS = 'PURGEKEYS';
42
43
    const HTTP_METHOD_REFRESH = 'GET';
44
45
    const HTTP_HEADER_HOST = 'X-Host';
46
47
    const HTTP_HEADER_URL = 'X-Url';
48
49
    const HTTP_HEADER_CONTENT_TYPE = 'X-Content-Type';
50
51
    /**
52
     * Default name of the header used to invalidate content with specific tags.
53
     *
54
     * This happens to be the same as TagHeaderFormatter::DEFAULT_HEADER_NAME
55
     * but does not technically need to be the same.
56
     *
57 4
     * @var string
58
     */
59 4
    const DEFAULT_HTTP_HEADER_CACHE_TAGS = 'X-Cache-Tags';
60
61 4
    /**
62
     * {@inheritdoc}
63
     */
64
    public function invalidateTags(array $tags)
65
    {
66 1
        $tagMode = $this->options['tag_mode'];
67 1
        $escapedTags = array_map('preg_quote', $this->escapeTags($tags));
68
69 3
        $chunkSize = $this->determineTagsPerHeader($escapedTags, 'ban' === $tagMode ? '|' : ' ');
70
71
        foreach (array_chunk($escapedTags, $chunkSize) as $tagchunk) {
72 4
            if ('ban' === $tagMode) {
73 4
                $tagExpression = sprintf('(^|,)(%s)(,|$)', implode('|', $tagchunk));
74 4
                $this->ban([$this->options['tags_header'] => $tagExpression]);
75
            } else {// purgekeys
76
                $this->queueRequest(
77 4
                    self::HTTP_METHOD_PURGEKEYS,
78
                    '/',
79
                    [$this->options['tags_header'] => implode(' ', $tagchunk)],
80
                    false
81
                );
82
            }
83 10
        }
84
85 10
        return $this;
86 10
    }
87 10
88
    /**
89
     * {@inheritdoc}
90 10
     */
91
    public function ban(array $headers)
92 10
    {
93
        $headers = array_merge(
94
            $this->options['default_ban_headers'],
95
            $headers
96
        );
97
98 4
        $this->queueRequest(self::HTTP_METHOD_BAN, '/', $headers, false);
99
100 4
        return $this;
101 2
    }
102 1
103
    /**
104 1
     * {@inheritdoc}
105
     */
106
    public function banPath($path, $contentType = null, $hosts = null)
107
    {
108 3
        if (is_array($hosts)) {
109
            if (!count($hosts)) {
110
                throw new InvalidArgumentException('Either supply a list of hosts or null, but not an empty array.');
111 3
            }
112 2
            $hosts = '^('.implode('|', $hosts).')$';
113
        }
114 3
115 1
        $headers = [
116
            self::HTTP_HEADER_URL => $path,
117
        ];
118 3
119
        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...
120
            $headers[self::HTTP_HEADER_CONTENT_TYPE] = $contentType;
121
        }
122
        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...
123
            $headers[self::HTTP_HEADER_HOST] = $hosts;
124 4
        }
125
126 4
        return $this->ban($headers);
127
    }
128 4
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function purge($url, array $headers = [])
133
    {
134 3
        $this->queueRequest(self::HTTP_METHOD_PURGE, $url, $headers);
135
136 3
        return $this;
137 3
    }
138
139 3
    /**
140
     * {@inheritdoc}
141
     */
142 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...
143
    {
144
        $headers = array_merge($headers, ['Cache-Control' => 'no-cache']);
145 19
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
146
147 19
        return $this;
148 19
    }
149 19
150 19
    /**
151
     * {@inheritdoc}
152
     */
153 19
    protected function configureOptions()
154 19
    {
155
        $resolver = parent::configureOptions();
156 19
        $resolver->setDefaults([
157 19
            'tags_header' => self::DEFAULT_HTTP_HEADER_CACHE_TAGS,
158 19
            'tag_mode' => 'ban',
159
            'header_length' => 7500,
160 19
            'default_ban_headers' => [],
161
        ]);
162 19
        // tag_mode options: 'ban' or 'purgekeys'
163
        $resolver->setAllowedValues('tag_mode', ['ban', 'purgekeys']);
164 19
        $resolver->setNormalizer('default_ban_headers', function ($resolver, $specified) {
165
            return array_merge(
166
                [
167
                    self::HTTP_HEADER_HOST => self::REGEX_MATCH_ALL,
168
                    self::HTTP_HEADER_URL => self::REGEX_MATCH_ALL,
169
                    self::HTTP_HEADER_CONTENT_TYPE => self::REGEX_MATCH_ALL,
170
                ],
171
                $specified
172
            );
173
        });
174
175
        return $resolver;
176
    }
177
}
178