Completed
Pull Request — master (#27)
by Adam
03:43
created

Client::on()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 4.0023

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 18
cts 19
cp 0.9474
rs 9.456
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\Discovery\MessageFactoryDiscovery;
11
use Http\Message\RequestMatcher;
12
use Http\Message\ResponseFactory;
13
use Psr\Http\Message\RequestInterface;
14
use Psr\Http\Message\ResponseInterface;
15
16
/**
17
 * An implementation of the HTTP client that is useful for automated tests.
18
 *
19
 * This mock does not send requests but stores them for later retrieval.
20
 * You can configure the mock with responses to return and/or exceptions to throw.
21
 *
22
 * @author David de Boer <[email protected]>
23
 */
24
class Client implements HttpClient, HttpAsyncClient
25
{
26
    use HttpAsyncClientEmulator;
27
    use VersionBridgeClient;
28
29
    /**
30
     * @var ResponseFactory
31
     */
32
    private $responseFactory;
33
34
    /**
35
     * @var array
36
     */
37
    private $conditionalResults = [];
38
39
    /**
40
     * @var RequestInterface[]
41
     */
42
    private $requests = [];
43
44
    /**
45
     * @var ResponseInterface[]
46
     */
47
    private $responses = [];
48
49
    /**
50
     * @var ResponseInterface|null
51
     */
52
    private $defaultResponse;
53
54
    /**
55
     * @var Exception[]
56
     */
57
    private $exceptions = [];
58
59
    /**
60
     * @var Exception|null
61
     */
62
    private $defaultException;
63
64 15
    public function __construct(ResponseFactory $responseFactory = null)
65
    {
66 15
        $this->responseFactory = $responseFactory ?: MessageFactoryDiscovery::find();
67 15
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 11
    public function doSendRequest(RequestInterface $request)
73
    {
74 11
        $this->requests[] = $request;
75
76 11
        foreach ($this->conditionalResults as $result) {
77
            /**
78
             * @var RequestMatcher
79
             */
80 4
            $matcher = $result['matcher'];
81
82
            /**
83
             * @var callable
84
             */
85 4
            $callable = $result['callable'];
86
87 4
            if ($matcher->matches($request)) {
88 4
                return $callable($request);
89
            }
90
        }
91
92 8
        if (count($this->exceptions) > 0) {
93 1
            throw array_shift($this->exceptions);
94
        }
95
96 7
        if (count($this->responses) > 0) {
97 3
            return array_shift($this->responses);
98
        }
99
100 4
        if ($this->defaultException) {
101 1
            throw $this->defaultException;
102
        }
103
104 3
        if ($this->defaultResponse) {
105 1
            return $this->defaultResponse;
106
        }
107
108
        // Return success response by default
109 2
        return $this->responseFactory->createResponse();
110
    }
111
112
    /**
113
     * Adds an exception to be thrown or response to be returned if the request matcher matches.
114
     *
115
     * For more complex logic, pass a callable which should take the request and return a response or exception
116
     *
117
     * @param RequestMatcher                        $requestMatcher
118
     * @param ResponseInterface|\Exception|callable $result
119
     */
120 4
    public function on(RequestMatcher $requestMatcher, $result)
121
    {
122 4
        $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...
123
124
        switch (true) {
125 4
            case is_callable($result):
126 1
                $callable = $result;
127
128 1
                break;
129 3
            case $result instanceof ResponseInterface:
130
                $callable = function () use ($result) {
131 1
                    return $result;
132 2
                };
133
134 2
                break;
135 1
            case $result instanceof \Exception:
136 1
                $callable = function () use ($result) {
137 1
                    throw $result;
138 1
                };
139
140 1
                break;
141
            default:
142
                throw new \InvalidArgumentException('Result must be either a response, an exception, or a callable');
143
        }
144 4
        $this->conditionalResults[] = [
145 4
            'matcher' => $requestMatcher,
146 4
            'callable' => $callable,
147
        ];
148 4
    }
149
150
    /**
151
     * Adds an exception that will be thrown.
152
     */
153 2 View Code Duplication
    public function addException(\Exception $exception)
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...
154
    {
155 2
        if (!$exception instanceof Exception) {
156
            @trigger_error('Clients may only throw exceptions of type '.Exception::class.'. Setting an exception of class '.get_class($exception).' will not be possible anymore in the future', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
157
        }
158
        $this->exceptions[] = $exception;
159
    }
160
161
    /**
162
     * Sets the default exception to throw when the list of added exceptions and responses is exhausted.
163
     *
164
     * If both a default exception and a default response are set, the exception will be thrown.
165
     */
166 View Code Duplication
    public function setDefaultException(\Exception $defaultException = null)
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...
167
    {
168
        if (!$defaultException instanceof Exception) {
169
            @trigger_error('Clients may only throw exceptions of type '.Exception::class.'. Setting an exception of class '.get_class($defaultException).' will not be possible anymore in the future', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
170
        }
171
        $this->defaultException = $defaultException;
0 ignored issues
show
Documentation Bug introduced by
It seems like $defaultException can also be of type object<Exception>. However, the property $defaultException is declared as type object<Http\Client\Exception>|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...
172
    }
173
174
    /**
175
     * Adds a response that will be returned in first in first out order.
176
     */
177
    public function addResponse(ResponseInterface $response)
178
    {
179
        $this->responses[] = $response;
180
    }
181
182
    /**
183
     * Sets the default response to be returned when the list of added exceptions and responses is exhausted.
184
     */
185
    public function setDefaultResponse(ResponseInterface $defaultResponse = null)
186
    {
187
        $this->defaultResponse = $defaultResponse;
188
    }
189
190
    /**
191
     * Returns requests that were sent.
192
     *
193
     * @return RequestInterface[]
194
     */
195
    public function getRequests()
196
    {
197
        return $this->requests;
198
    }
199
200
    public function getLastRequest()
201
    {
202
        return end($this->requests);
203
    }
204
205
    public function reset()
206
    {
207
        $this->responses = [];
208
        $this->exceptions = [];
209
        $this->requests = [];
210
        $this->setDefaultException();
211
        $this->setDefaultResponse();
212
    }
213
}
214