Completed
Push — master ( 2bb76e...2f6bf5 )
by Maksim
03:40
created

ProxyResolver::remove()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
namespace Liip\ImagineBundle\Imagine\Cache\Resolver;
4
5
use Liip\ImagineBundle\Binary\BinaryInterface;
6
7
/**
8
 * ProxyResolver.
9
 *
10
 * @author Robert Schönthal <[email protected]>
11
 */
12
class ProxyResolver implements ResolverInterface
13
{
14
    /**
15
     * @var ResolverInterface
16
     */
17
    protected $resolver;
18
19
    /**
20
     * a list of proxy hosts (picks a random one for each generation to seed browser requests among multiple hosts).
21
     *
22
     * @var array
23
     */
24
    protected $hosts = array();
25
26
    /**
27
     * @param ResolverInterface $resolver
28
     * @param string[]          $hosts
29
     */
30
    public function __construct(ResolverInterface $resolver, array $hosts)
31
    {
32
        $this->resolver = $resolver;
33
        $this->hosts = $hosts;
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function resolve($path, $filter)
40
    {
41
        return $this->rewriteUrl($this->resolver->resolve($path, $filter));
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function store(BinaryInterface $binary, $targetPath, $filter)
48
    {
49
        return $this->resolver->store($binary, $targetPath, $filter);
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function isStored($path, $filter)
56
    {
57
        return $this->resolver->isStored($path, $filter);
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function remove(array $paths, array $filters)
64
    {
65
        return $this->resolver->remove($paths, $filters);
66
    }
67
68
    /**
69
     * @param $url
70
     *
71
     * @return string
72
     */
73
    protected function rewriteUrl($url)
74
    {
75
        if (empty($this->hosts)) {
76
            return $url;
77
        }
78
79
        $randKey = array_rand($this->hosts, 1);
80
81
        // BC
82
        if (is_numeric($randKey)) {
83
            $host = parse_url($url, PHP_URL_SCHEME).'://'.parse_url($url, PHP_URL_HOST);
84
            $proxyHost = $this->hosts[$randKey];
85
86
            return str_replace($host, $proxyHost, $url);
87
        }
88
89
        if (0 === strpos($randKey, 'regexp/')) {
90
            $regExp = substr($randKey, 6);
91
92
            return preg_replace($regExp, $this->hosts[$randKey], $url);
93
        }
94
95
        return str_replace($randKey, $this->hosts[$randKey], $url);
96
    }
97
}
98