Completed
Pull Request — master (#332)
by André
03:00
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 0
Metric Value
dl 7
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
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\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
    const HTTP_METHOD_PURGE = 'PURGE';
39
    const HTTP_METHOD_REFRESH = 'GET';
40
    const HTTP_HEADER_HOST = 'X-Host';
41
    const HTTP_HEADER_URL = 'X-Url';
42
    const HTTP_HEADER_CONTENT_TYPE = 'X-Content-Type';
43
44
    /**
45
     * Default name of the header used to invalidate content with specific tags.
46
     *
47
     * This happens to be the same as TagHeaderFormatter::DEFAULT_HEADER_NAME
48
     * but does not technically need to be the same.
49
     *
50
     * @var string
51
     */
52
    const DEFAULT_HTTP_HEADER_CACHE_TAGS = 'X-Cache-Tags';
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 4
    public function invalidateTags(array $tags)
58
    {
59 4
        $tagMode = $this->options['tag_mode'];
60
        $escapedTags = array_map('preg_quote', $this->escapeTags($tags));
61 4
62
        if ($tagMode === 'purge_single') {
63
            $elems = 1;
64
        } elseif (mb_strlen(implode('|', $escapedTags)) >= $this->options['header_length']) {
65
            /*
66 1
             * estimate the amount of tags to invalidate by dividing the max
67 1
             * header length by the largest tag (minus 1 for the implode character)
68
             */
69 3
            $tagsize = max(array_map('mb_strlen', $escapedTags));
70
            $elems = floor($this->options['header_length'] / ($tagsize - 1)) ?: 1;
71
        } else {
72 4
            $elems = count($escapedTags);
73 4
        }
74 4
75
        foreach (array_chunk($escapedTags, $elems) as $tagchunk) {
76
            if ($tagMode === 'ban') {
77 4
                $tagExpression = sprintf('(%s)(,|$)', implode('|', $tagchunk));
78
                $this->ban([$this->options['tags_header'] => $tagExpression]);
79
            } else {
80
                $this->queueRequest(
81
                    self::HTTP_METHOD_PURGE,
82
                    '/',
83 10
                    [$this->options['tags_header'] => implode(' ', $tagchunk)],
84
                    false
85 10
                );
86 10
            }
87 10
        }
88
89
        return $this;
90 10
    }
91
92 10
    /**
93
     * {@inheritdoc}
94
     */
95
    public function ban(array $headers)
96
    {
97
        $headers = array_merge(
98 4
            $this->options['default_ban_headers'],
99
            $headers
100 4
        );
101 2
102 1
        $this->queueRequest(self::HTTP_METHOD_BAN, '/', $headers, false);
103
104 1
        return $this;
105
    }
106
107
    /**
108 3
     * {@inheritdoc}
109
     */
110
    public function banPath($path, $contentType = null, $hosts = null)
111 3
    {
112 2
        if (is_array($hosts)) {
113
            if (!count($hosts)) {
114 3
                throw new InvalidArgumentException('Either supply a list of hosts or null, but not an empty array.');
115 1
            }
116
            $hosts = '^('.implode('|', $hosts).')$';
117
        }
118 3
119
        $headers = [
120
            self::HTTP_HEADER_URL => $path,
121
        ];
122
123
        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 4
            $headers[self::HTTP_HEADER_CONTENT_TYPE] = $contentType;
125
        }
126 4
        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
            $headers[self::HTTP_HEADER_HOST] = $hosts;
128 4
        }
129
130
        return $this->ban($headers);
131
    }
132
133
    /**
134 3
     * {@inheritdoc}
135
     */
136 3
    public function purge($url, array $headers = [])
137 3
    {
138
        $this->queueRequest(self::HTTP_METHOD_PURGE, $url, $headers);
139 3
140
        return $this;
141
    }
142
143
    /**
144
     * {@inheritdoc}
145 19
     */
146 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 19
    {
148 19
        $headers = array_merge($headers, ['Cache-Control' => 'no-cache']);
149 19
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
150 19
151
        return $this;
152
    }
153 19
154 19
    /**
155
     * {@inheritdoc}
156 19
     */
157 19
    protected function configureOptions()
158 19
    {
159
        $resolver = parent::configureOptions();
160 19
        $resolver->setDefaults([
161
            'tags_header' => self::DEFAULT_HTTP_HEADER_CACHE_TAGS,
162 19
            'tag_mode' => 'ban',
163
            'header_length' => 7500,
164 19
            'default_ban_headers' => [],
165
        ]);
166
        // tag_mode options: 'ban', 'purge', or 'purge_single' for purge invalidation per tag
167
        $resolver->setAllowedValues('tag_mode', ['ban', 'purge', 'purge_single']);
168
        $resolver->setNormalizer('default_ban_headers', function ($resolver, $specified) {
169
            return array_merge(
170
                [
171
                    self::HTTP_HEADER_HOST => self::REGEX_MATCH_ALL,
172
                    self::HTTP_HEADER_URL => self::REGEX_MATCH_ALL,
173
                    self::HTTP_HEADER_CONTENT_TYPE => self::REGEX_MATCH_ALL,
174
                ],
175
                $specified
176
            );
177
        });
178
179
        return $resolver;
180
    }
181
}
182