Test Setup Failed
Branch 0.x (5da7af)
by Pavel
13:48
created

Alfred   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 57
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getProxy() 0 13 2
A resolveProxyList() 0 11 2
1
<?php
2
3
/*
4
 * This file is part of the Veslo project <https://github.com/symfony-doge/veslo>.
5
 *
6
 * (C) 2019 Pavel Petrov <[email protected]>.
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 *
11
 * @license https://opensource.org/licenses/GPL-3.0 GPL-3.0
12
 */
13
14
declare(strict_types=1);
15
16
namespace Veslo\AppBundle\Http\Proxy\Manager;
17
18
use Veslo\AppBundle\Exception\Http\ProxyNotFoundException;
19
use Veslo\AppBundle\Http\Proxy\LocatorInterface;
20
21
/**
22
 * Provides a proxy for http requests
23
 */
24
class Alfred
25
{
26
    /**
27
     * Provides a list with available proxies for http requests
28
     *
29
     * @var LocatorInterface
30
     */
31
    private $proxyLocator;
32
33
    /**
34
     * Alfred constructor.
35
     *
36
     * @param LocatorInterface $proxyLocator Uses a simple array node from configuration file to provide proxy list
37
     */
38
    public function __construct(LocatorInterface $proxyLocator)
39
    {
40
        $this->proxyLocator = $proxyLocator;
41
    }
42
43
    /**
44
     * Returns proxy for http requests
45
     *
46
     * @return string
47
     *
48
     * @throws ProxyNotFoundException
49
     */
50
    public function getProxy(): string
51
    {
52
        $numericProxyList = $this->resolveProxyList();
53
54
        if (0 >= count($numericProxyList)) {
55
            throw new ProxyNotFoundException();
56
        }
57
58
        $randomIndex = mt_rand(0, count($numericProxyList) - 1);
59
        $proxy       = $numericProxyList[$randomIndex];
60
61
        return $proxy;
62
    }
63
64
    /**
65
     * Returns numeric array with all available proxies
66
     *
67
     * @return string[]
68
     */
69
    private function resolveProxyList(): array
70
    {
71
        $proxyList        = $this->proxyLocator->locate(); // iterable
72
        $numericProxyList = [];
73
74
        foreach ($proxyList as $proxyUri) {
75
            $numericProxyList[] = $proxyUri;
76
        }
77
78
        return $numericProxyList;
79
    }
80
}
81