Completed
Pull Request — master (#332)
by André
15:21 queued 13:27
created

Varnish   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 150
Duplicated Lines 4.67 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 94.44%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 3
dl 7
loc 150
ccs 51
cts 54
cp 0.9444
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getTagsHeaderName() 0 4 1
A ban() 0 11 1
A purge() 0 6 1
A refresh() 7 7 1
B invalidateTags() 0 31 6
A getTagsHeaderValue() 0 4 1
B banPath() 0 22 5
A configureOptions() 0 23 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\BanInterface;
16
use FOS\HttpCache\ProxyClient\Invalidation\PurgeInterface;
17
use FOS\HttpCache\ProxyClient\Invalidation\RefreshInterface;
18
use FOS\HttpCache\ProxyClient\Invalidation\TagsInterface;
19
20
/**
21
 * Varnish HTTP cache invalidator.
22
 *
23
 * Additional constructor options:
24
 * - tags_header         Header for tagging responses, defaults to X-Cache-Tags
25
 * - header_length       Maximum header length, defaults to 7500 bytes
26
 * - default_ban_headers Map of headers that are set on each ban request,
27
 *                       merged with the built-in headers
28
 *
29
 * @author David de Boer <[email protected]>
30
 */
31
class Varnish extends HttpProxyClient 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
    const DEFAULT_HTTP_HEADER_CACHE_TAGS = 'X-Cache-Tags';
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 4
    public function invalidateTags(array $tags)
45
    {
46 4
        if ($this->options['tags_invalidation_by_purge']) {
47
            // Varnish xkey (and Fastly) is limited to purge one tag at a time
48
            foreach (array_unique($this->escapeTags($tags)) as $tag) {
49
                $this->purge('/', [$this->options['tags_header'] => $tag]);
50
            }
51
52
            return $this;
53
        }
54
55 4
        $escapedTags = array_map('preg_quote', $this->escapeTags($tags));
56
57 4
        if (mb_strlen(implode('|', $escapedTags)) >= $this->options['header_length']) {
58
            /*
59
             * estimate the amount of tags to invalidate by dividing the max
60
             * header length by the largest tag (minus 1 for the implode character)
61
             */
62 1
            $tagsize = max(array_map('mb_strlen', $escapedTags));
63 1
            $elems = floor($this->options['header_length'] / ($tagsize - 1)) ?: 1;
64
        } else {
65 3
            $elems = count($escapedTags);
66
        }
67
68 4
        foreach (array_chunk($escapedTags, $elems) as $tagchunk) {
69 4
            $tagExpression = sprintf('(%s)(,.+)?$', implode('|', $tagchunk));
70 4
            $this->ban([$this->options['tags_header'] => $tagExpression]);
71
        }
72
73 4
        return $this;
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79 1
    public function getTagsHeaderValue(array $tags)
80
    {
81 1
        return implode($this->options['tags_separator'], array_unique($this->escapeTags($tags)));
82
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87 1
    public function getTagsHeaderName()
88
    {
89 1
        return $this->options['tags_header'];
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     */
95 10
    public function ban(array $headers)
96
    {
97 10
        $headers = array_merge(
98 10
            $this->options['default_ban_headers'],
99
            $headers
100
        );
101
102 10
        $this->queueRequest(self::HTTP_METHOD_BAN, '/', $headers);
103
104 10
        return $this;
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110 4
    public function banPath($path, $contentType = null, $hosts = null)
111
    {
112 4
        if (is_array($hosts)) {
113 2
            if (!count($hosts)) {
114 1
                throw new InvalidArgumentException('Either supply a list of hosts or null, but not an empty array.');
115
            }
116 1
            $hosts = '^('.implode('|', $hosts).')$';
117
        }
118
119
        $headers = [
120 3
            self::HTTP_HEADER_URL => $path,
121
        ];
122
123 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...
124 2
            $headers[self::HTTP_HEADER_CONTENT_TYPE] = $contentType;
125
        }
126 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...
127 1
            $headers[self::HTTP_HEADER_HOST] = $hosts;
128
        }
129
130 3
        return $this->ban($headers);
131
    }
132
133
    /**
134
     * {@inheritdoc}
135
     */
136 4
    public function purge($url, array $headers = [])
137
    {
138 4
        $this->queueRequest(self::HTTP_METHOD_PURGE, $url, $headers);
139
140 4
        return $this;
141
    }
142
143
    /**
144
     * {@inheritdoc}
145
     */
146 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...
147
    {
148 3
        $headers = array_merge($headers, ['Cache-Control' => 'no-cache']);
149 3
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
150
151 3
        return $this;
152
    }
153
154
    /**
155
     * {@inheritdoc}
156
     */
157 22
    protected function configureOptions()
158
    {
159 22
        $resolver = parent::configureOptions();
160 22
        $resolver->setDefaults([
161 22
            'tags_header' => self::DEFAULT_HTTP_HEADER_CACHE_TAGS,
162 22
            'header_length' => 7500,
163
            'tags_invalidation_by_purge' => false,
164 22
            'tags_separator' => ',',
165
            'default_ban_headers' => [],
166
        ]);
167 22
        $resolver->setNormalizer('default_ban_headers', function ($resolver, $specified) {
168 22
            return array_merge(
169
                [
170 22
                    self::HTTP_HEADER_HOST => self::REGEX_MATCH_ALL,
171 22
                    self::HTTP_HEADER_URL => self::REGEX_MATCH_ALL,
172 22
                    self::HTTP_HEADER_CONTENT_TYPE => self::REGEX_MATCH_ALL,
173
                ],
174
                $specified
175
            );
176 22
        });
177
178 22
        return $resolver;
179
    }
180
}
181