Completed
Push — master ( fceab7...09c4c4 )
by Fabian
13s
created

DispatchAllReturnFirstSuccess::execute()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 7
cts 7
cp 1
rs 9.7333
c 0
b 0
f 0
cc 4
nc 3
nop 5
crap 4
1
<?php
2
declare(strict_types=1);
3
4
namespace IntegerNet\CallbackProxy\DispatchStrategy;
5
6
use IntegerNet\CallbackProxy\DispatchStrategy;
7
use IntegerNet\CallbackProxy\HttpClient;
8
use IntegerNet\CallbackProxy\Targets;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
12
class DispatchAllReturnFirstSuccess implements DispatchStrategy
13
{
14 42
    public function execute(
15
        HttpClient $client,
16
        Targets $targets,
17
        RequestInterface $request,
18
        ResponseInterface $response,
19
        string $action
20
    ): ResponseInterface {
21 42
        $firstSuccessfulResponse = null;
22 42
        foreach ($targets as $target) {
23 42
            $response = $client->send($request, $target, $action);
24 42
            if ($firstSuccessfulResponse === null && $this->responseIsSuccessful($response)) {
25 42
                $firstSuccessfulResponse = $response;
26
            }
27
        }
28 42
        return $firstSuccessfulResponse ?? $response;
29
    }
30
31 42
    private function responseIsSuccessful(ResponseInterface $response): bool
32
    {
33 42
        return $response->getStatusCode() >= 200 && $response->getStatusCode() < 300;
34
    }
35
}
36