Completed
Pull Request — master (#312)
by David
11:09
created

Varnish::configureOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
ccs 13
cts 13
cp 1
cc 1
eloc 13
nc 1
nop 0
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\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
    public function invalidateTags(array $tags)
45
    {
46
        $escapedTags = array_map('preg_quote', $this->escapeTags($tags));
47
48
        if (mb_strlen(implode('|', $escapedTags)) >= $this->options['header_length']) {
49
            /*
50
             * estimate the amount of tags to invalidate by dividing the max
51
             * header length by the largest tag (minus 1 for the implode character)
52
             */
53
            $tagsize = max(array_map('mb_strlen', $escapedTags));
54
            $elems = floor($this->options['header_length'] / ($tagsize - 1)) ?: 1;
55
        } else {
56
            $elems = count($escapedTags);
57 2
        }
58
59 2
        foreach (array_chunk($escapedTags, $elems) as $tagchunk) {
60 2
            $tagExpression = sprintf('(%s)(,.+)?$', implode('|', $tagchunk));
61
            $this->ban([$this->options['tags_header'] => $tagExpression]);
62
        }
63
64
        return $this;
65
    }
66
67
    /**
68 2
     * {@inheritdoc}
69
     */
70 2
    public function getTagsHeaderValue(array $tags)
71 2
    {
72
        return implode(',', array_unique($this->escapeTags($tags)));
73
    }
74
75
    /**
76 4
     * {@inheritdoc}
77
     */
78 4
    public function getTagsHeaderName()
79
    {
80 4
        return $this->options['tags_header'];
81
    }
82
83
    /**
84
     * {@inheritdoc}
85 1
     */
86 1
    public function ban(array $headers)
87 1
    {
88 3
        $headers = array_merge(
89
            $this->options['default_ban_headers'],
90
            $headers
91 4
        );
92 4
93 4
        $this->queueRequest(self::HTTP_METHOD_BAN, '/', $headers);
94 4
95
        return $this;
96 4
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101
    public function banPath($path, $contentType = null, $hosts = null)
102
    {
103
        if (is_array($hosts)) {
104
            if (!count($hosts)) {
105
                throw new InvalidArgumentException('Either supply a list of hosts or null, but not an empty array.');
106
            }
107
            $hosts = '^('.implode('|', $hosts).')$';
108
        }
109
110
        $headers = [
111
            self::HTTP_HEADER_URL => $path,
112 1
        ];
113
114 1
        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...
115
            $headers[self::HTTP_HEADER_CONTENT_TYPE] = $contentType;
116
        }
117
        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...
118
            $headers[self::HTTP_HEADER_HOST] = $hosts;
119
        }
120
121
        return $this->ban($headers);
122 1
    }
123
124 1
    /**
125
     * {@inheritdoc}
126
     */
127
    public function purge($url, array $headers = [])
128
    {
129
        $this->queueRequest(self::HTTP_METHOD_PURGE, $url, $headers);
130 12
131
        return $this;
132 12
    }
133 12
134
    /**
135 12
     * {@inheritdoc}
136
     */
137 12 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...
138
    {
139 12
        $headers = array_merge($headers, ['Cache-Control' => 'no-cache']);
140
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
141
142
        return $this;
143
    }
144
145 4
    /**
146
     * {@inheritdoc}
147 4
     */
148 2
    protected function configureOptions()
149 1
    {
150
        $resolver = parent::configureOptions();
151 1
        $resolver->setDefaults([
152 1
            'tags_header' => self::DEFAULT_HTTP_HEADER_CACHE_TAGS,
153
            'header_length' => 7500,
154
            'default_ban_headers' => [],
155 3
        ]);
156 3
        $resolver->setNormalizer('default_ban_headers', function ($resolver, $specified) {
157
            return array_merge(
158 3
                [
159 2
                    self::HTTP_HEADER_HOST => self::REGEX_MATCH_ALL,
160 2
                    self::HTTP_HEADER_URL => self::REGEX_MATCH_ALL,
161 3
                    self::HTTP_HEADER_CONTENT_TYPE => self::REGEX_MATCH_ALL,
162 1
                ],
163 1
                $specified
164
            );
165 3
        });
166
167
        return $resolver;
168
    }
169
}
170