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

ProxyResolver   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 2
Bugs 1 Features 1
Metric Value
wmc 9
c 2
b 1
f 1
lcom 1
cbo 1
dl 0
loc 86
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A resolve() 0 4 1
A store() 0 4 1
A isStored() 0 4 1
A remove() 0 4 1
B rewriteUrl() 0 24 4
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