Completed
Push — master ( 79bb1d...7eb253 )
by BENOIT
01:42
created

FunnelHttpClient   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 96
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 3
dl 0
loc 96
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A request() 0 14 3
A stream() 0 4 1
A waitUntilReady() 0 11 2
A throttle() 0 4 1
1
<?php
2
3
namespace BenTools\FunnelHttpClient;
4
5
use BenTools\FunnelHttpClient\Storage\ArrayStorage;
6
use BenTools\FunnelHttpClient\Storage\ThrottleStorageInterface;
7
use BenTools\FunnelHttpClient\Strategy\AlwaysThrottleStrategy;
8
use BenTools\FunnelHttpClient\Strategy\ThrottleStrategyInterface;
9
use Psr\Log\LoggerInterface;
10
use Psr\Log\NullLogger;
11
use Symfony\Contracts\HttpClient\HttpClientInterface;
12
use Symfony\Contracts\HttpClient\ResponseInterface;
13
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
14
15
final class FunnelHttpClient implements HttpClientInterface
16
{
17
    /**
18
     * @var HttpClientInterface
19
     */
20
    private $decorated;
21
22
    /**
23
     * @var ThrottleStorageInterface
24
     */
25
    private $throttleStorage;
26
27
    /**
28
     * @var ThrottleStrategyInterface|null
29
     */
30
    private $throttleStrategy;
31
32
    /**
33
     * @var LoggerInterface|null
34
     */
35
    private $logger;
36
37
    /**
38
     * FunnelHttpClient constructor.
39
     *
40
     * @param HttpClientInterface            $decorated
41
     * @param ThrottleStorageInterface       $throttleStorage
42
     * @param ThrottleStrategyInterface|null $throttleStrategy
43
     * @param LoggerInterface|null           $logger
44
     */
45
    public function __construct(
46
        HttpClientInterface $decorated,
47
        ThrottleStorageInterface $throttleStorage,
48
        ?ThrottleStrategyInterface $throttleStrategy = null,
49
        ?LoggerInterface $logger = null
50
    ) {
51
        $this->decorated = $decorated;
52
        $this->throttleStorage = $throttleStorage;
53
        $this->throttleStrategy = $throttleStrategy ?? new AlwaysThrottleStrategy();
54
        $this->logger = $logger ?? new NullLogger();
0 ignored issues
show
Documentation Bug introduced by
It seems like $logger ?? new \Psr\Log\NullLogger() can also be of type object<Psr\Log\NullLogger>. However, the property $logger is declared as type object<Psr\Log\LoggerInterface>|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
55
    }
56
57
    /**
58
     * @inheritDoc
59
     */
60
    public function request(string $method, string $url, array $options = []): ResponseInterface
61
    {
62
        if (!$this->throttleStrategy->shouldThrottle($method, $url, $options)) {
63
            return $this->decorated->request($method, $url, $options);
64
        }
65
66
        if (0 === $this->throttleStorage->getRemainingCalls()) {
67
            $this->waitUntilReady($method, $url);
68
        }
69
70
        $response = $this->decorated->request($method, $url, $options);
71
        $this->throttleStorage->increment();
72
        return $response;
73
    }
74
75
    /**
76
     * @inheritDoc
77
     */
78
    public function stream($responses, float $timeout = null): ResponseStreamInterface
79
    {
80
        return $this->decorated->stream($responses, $timeout);
81
    }
82
83
    /**
84
     * @param string $method
85
     * @param string $url
86
     */
87
    private function waitUntilReady(string $method, string $url): void
88
    {
89
        $remainingSeconds = $this->throttleStorage->getRemainingTime();
90
        $this->logger->info(\sprintf('Max requests / window reached. Waiting %s seconds...', $remainingSeconds), ['method' => $method, 'url' => $url]);
91
92
        if (0 === ($remainingSeconds <=> (int) $remainingSeconds)) {
93
            \sleep((int) $remainingSeconds);
94
        } else {
95
            \usleep((int) \round($remainingSeconds * 1000000));
96
        }
97
    }
98
99
    /**
100
     * @param HttpClientInterface  $client
101
     * @param int                  $maxRequests
102
     * @param float                $timeWindow
103
     * @param LoggerInterface|null $logger
104
     * @return FunnelHttpClient
105
     */
106
    public static function throttle(HttpClientInterface $client, int $maxRequests, float $timeWindow, ?LoggerInterface $logger = null): self
107
    {
108
        return new self($client, new ArrayStorage($maxRequests, $timeWindow), null, $logger);
109
    }
110
}
111