Completed
Pull Request — master (#42)
by Andreas
05:56 queued 04:39
created

StrictClient::on()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 30

Duplication

Lines 30
Ratio 100 %

Code Coverage

Tests 18
CRAP Score 4.0023

Importance

Changes 0
Metric Value
dl 30
loc 30
ccs 18
cts 19
cp 0.9474
rs 9.44
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4.0023
1
<?php
2
3
namespace Http\Mock;
4
5
use Http\Client\Common\HttpAsyncClientEmulator;
6
use Http\Client\Common\VersionBridgeClient;
7
use Http\Client\Exception;
8
use Http\Client\HttpAsyncClient;
9
use Http\Client\HttpClient;
10
use Http\Message\RequestMatcher;
11
use Http\Mock\Exception\RequestMismatchException;
12
use Http\Mock\Exception\UnexpectedRequestException;
13
use Psr\Http\Client\ClientExceptionInterface;
14
use Psr\Http\Message\RequestInterface;
15
use Psr\Http\Message\ResponseInterface;
16
17
/**
18
 * An implementation of the HTTP client that is useful for automated tests.
19
 *
20
 * This mock expects requests to be sent in a sequence and returns responses or throws exceptions as configured.
21
 *
22
 * @author Andreas Möller <[email protected]>
23
 */
24
class StrictClient implements HttpClient, HttpAsyncClient
25
{
26
    use HttpAsyncClientEmulator;
27
    use VersionBridgeClient;
28
29
    /**
30
     * @var array
31
     */
32
    private $configuredSequence = [];
33
34
    /**
35
     * {@inheritdoc}
36
     *
37
     * @throws UnexpectedRequestException
38
     * @throws RequestMismatchException
39
     */
40 8
    public function doSendRequest(RequestInterface $request)
41
    {
42 8
        $next = array_shift($this->configuredSequence);
43
44 8
        if (null === $next) {
45 1
            throw UnexpectedRequestException::fromRequest($request);
46
        }
47
48
        /** @var RequestMatcher $matcher */
49 7
        $matcher = $next['matcher'];
50
51
        try {
52 7
            $isMatch = $matcher->matches($request);
53 1
        } catch (\Exception $exception) {
54 1
            throw RequestMismatchException::fromMatcherException($exception);
55
        }
56
57 6
        if (false === $isMatch) {
58 1
            throw RequestMismatchException::create();
59
        }
60
61
        /** @var callable $callable */
62 5
        $callable = $next['callable'];
63
64 5
        return $callable($request);
65
    }
66
67
    /**
68
     * Adds an exception to be thrown or response to be returned for the next request
69
     * expected to be sent in a sequence of requests.
70
     *
71
     * For more complex logic, pass a callable as $result. The method is given
72
     * the request and MUST either return a ResponseInterface or throw an
73
     * exception that implements the PSR-18 / HTTPlug exception interface.
74
     *
75
     * @param ResponseInterface|Exception|ClientExceptionInterface|callable $result
76
     */
77 7 View Code Duplication
    public function on(RequestMatcher $requestMatcher, $result)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
78
    {
79 7
        $callable = null;
0 ignored issues
show
Unused Code introduced by
$callable is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
80
81
        switch (true) {
82 7
            case is_callable($result):
83 1
                $callable = $result;
84
85 1
                break;
86 6
            case $result instanceof ResponseInterface:
87
                $callable = function () use ($result) {
88 3
                    return $result;
89 5
                };
90
91 5
                break;
92 1
            case $result instanceof \Exception:
93 1
                $callable = function () use ($result) {
94 1
                    throw $result;
95 1
                };
96
97 1
                break;
98
            default:
99
                throw new \InvalidArgumentException('Result must be either a response, an exception, or a callable');
100
        }
101
102 7
        $this->configuredSequence[] = [
103 7
            'matcher' => $requestMatcher,
104 7
            'callable' => $callable,
105
        ];
106 7
    }
107
108
    /**
109
     * Returns true when the configured sequence of requests and responses (or exceptions)
110
     * has been completed, i.e., the queue of configured results has been exhausted.
111
     *
112
     * @return bool
113
     */
114 3
    public function hasCompletedSequence()
115
    {
116 3
        return 0 === count($this->configuredSequence);
117
    }
118
}
119