Completed
Pull Request — master (#298)
by Jonas
05:25
created

Nginx::refresh()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 0
cts 6
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
crap 2
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\ProxyClient\Invalidation\PurgeInterface;
15
use FOS\HttpCache\ProxyClient\Invalidation\RefreshInterface;
16
17
/**
18
 * NGINX HTTP cache invalidator.
19
 *
20
 * @author Simone Fumagalli <[email protected]>
21
 */
22
class Nginx extends AbstractProxyClient implements PurgeInterface, RefreshInterface
23
{
24
    const HTTP_METHOD_PURGE = 'PURGE';
25
    const HTTP_METHOD_REFRESH = 'GET';
26
    const HTTP_HEADER_REFRESH = 'X-Refresh';
27
28
    /**
29
     * Path location that triggers purging. If false, same location purging is
30
     * assumed.
31
     *
32
     * @var string|false
33
     */
34
    private $purgeLocation;
35
36
    /**
37
     * Set path that triggers purge.
38
     *
39
     * @param string $purgeLocation
40
     */
41
    public function setPurgeLocation($purgeLocation = '')
42
    {
43
        $this->purgeLocation = (string) $purgeLocation;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function refresh($url, array $headers = [])
50
    {
51
        $headers = array_merge($headers, [self::HTTP_HEADER_REFRESH => '1']);
52
        $this->queueRequest(self::HTTP_METHOD_REFRESH, $url, $headers);
53
54
        return $this;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function purge($url, array $headers = [])
61
    {
62
        $purgeUrl = $this->buildPurgeUrl($url);
63
        $this->queueRequest(self::HTTP_METHOD_PURGE, $purgeUrl, $headers);
64
65
        return $this;
66
    }
67
68
    /**
69
     * Create the correct URL to purge a resource.
70
     *
71
     *
72
     * @param string $url URL
73
     *
74
     * @return string Rewritten URL
75
     */
76
    private function buildPurgeUrl($url)
77
    {
78
        if (empty($this->purgeLocation)) {
79
            return $url;
80
        }
81
82
        $urlParts = parse_url($url);
83
84
        if (isset($urlParts['host'])) {
85
            $pathStartAt = strpos($url, $urlParts['path']);
86
            $purgeUrl = substr($url, 0, $pathStartAt).$this->purgeLocation.substr($url, $pathStartAt);
87
        } else {
88
            $purgeUrl = $this->purgeLocation.$url;
89
        }
90
91
        return $purgeUrl;
92
    }
93
}
94