ServerPoolClient::get()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
namespace Surfnet\YubikeyApiClient\Http;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\RequestException;
7
use Psr\Http\Message\ResponseInterface;
8
9
class ServerPoolClient
10
{
11
    private static $serverPool = [
12
        'https://api.yubico.com/wsapi/2.0/verify',
13
        'https://api2.yubico.com/wsapi/2.0/verify',
14
        'https://api3.yubico.com/wsapi/2.0/verify',
15
        'https://api4.yubico.com/wsapi/2.0/verify',
16
        'https://api5.yubico.com/wsapi/2.0/verify',
17
    ];
18
19
    /**
20
     * @var Client
21
     */
22
    private $guzzleClient;
23
24
    /**
25
     * @param Client $guzzleClient
26
     */
27
    public function __construct(Client $guzzleClient)
28
    {
29
        $this->guzzleClient = $guzzleClient;
30
    }
31
32
    /**
33
     * @param array $requestOptions
34
     * @return ResponseInterface
35
     */
36
    public function get(array $requestOptions)
37
    {
38
        $poolIndex = array_rand(self::$serverPool);
39
        try {
40
            return $this->guzzleClient->get(self::$serverPool[$poolIndex], $requestOptions);
41
        } catch (RequestException $e) {
42
            if ($e->getResponse()) {
43
                throw $e;
44
            }
45
        }
46
47
        // There is no server response (timeout, DNS failure); try again.
48
        $poolIndex = ($poolIndex + 1) % count(self::$serverPool);
49
50
        return $this->guzzleClient->get(self::$serverPool[$poolIndex], $requestOptions);
51
    }
52
53
    public function getServerPool()
54
    {
55
        return self::$serverPool;
56
    }
57
}
58