Completed
Push — master ( 407890...740229 )
by David
03:09 queued 11s
created

Client::getRequests()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
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\ResponseFactory;
12
use Psr\Http\Message\RequestInterface;
13
use Psr\Http\Message\ResponseInterface;
14
15
/**
16
 * An implementation of the HTTP client that is useful for automated tests.
17
 *
18
 * This mock does not send requests but stores them for later retrieval.
19
 * You can configure the mock with responses to return and/or exceptions to throw.
20
 *
21
 * @author David de Boer <[email protected]>
22
 */
23
class Client implements HttpClient, HttpAsyncClient
24
{
25
    use HttpAsyncClientEmulator;
26
    use VersionBridgeClient;
27
28
    /**
29
     * @var ResponseFactory
30
     */
31
    private $responseFactory;
32
33
    /**
34
     * @var RequestInterface[]
35
     */
36
    private $requests = [];
37
38
    /**
39
     * @var ResponseInterface[]
40
     */
41
    private $responses = [];
42
43
    /**
44
     * @var ResponseInterface|null
45
     */
46
    private $defaultResponse;
47
48
    /**
49
     * @var Exception[]
50
     */
51
    private $exceptions = [];
52
53
    /**
54
     * @var Exception|null
55
     */
56
    private $defaultException;
57
58 11
    public function __construct(ResponseFactory $responseFactory = null)
59
    {
60 11
        $this->responseFactory = $responseFactory ?: MessageFactoryDiscovery::find();
61 11
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 7
    public function doSendRequest(RequestInterface $request)
67
    {
68 7
        $this->requests[] = $request;
69
70 7
        if (count($this->exceptions) > 0) {
71 1
            throw array_shift($this->exceptions);
72
        }
73
74 6
        if (count($this->responses) > 0) {
75 2
            return array_shift($this->responses);
76
        }
77
78 4
        if ($this->defaultException) {
79 1
            throw $this->defaultException;
80
        }
81
82 3
        if ($this->defaultResponse) {
83 1
            return $this->defaultResponse;
84
        }
85
86
        // Return success response by default
87 2
        return $this->responseFactory->createResponse();
88
    }
89
90
    /**
91
     * Adds an exception that will be thrown.
92
     */
93 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...
94
    {
95 2
        if (!$exception instanceof Exception) {
96
            @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...
97
        }
98
        $this->exceptions[] = $exception;
99
    }
100
101
    /**
102
     * Sets the default exception to throw when the list of added exceptions and responses is exhausted.
103
     *
104
     * If both a default exception and a default response are set, the exception will be thrown.
105
     */
106 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...
107
    {
108
        if (!$defaultException instanceof Exception) {
109
            @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...
110
        }
111
        $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...
112
    }
113
114
    /**
115
     * Adds a response that will be returned in first in first out order.
116
     */
117
    public function addResponse(ResponseInterface $response)
118
    {
119
        $this->responses[] = $response;
120
    }
121
122
    /**
123
     * Sets the default response to be returned when the list of added exceptions and responses is exhausted.
124
     */
125
    public function setDefaultResponse(ResponseInterface $defaultResponse = null)
126
    {
127
        $this->defaultResponse = $defaultResponse;
128
    }
129
130
    /**
131
     * Returns requests that were sent.
132
     *
133
     * @return RequestInterface[]
134
     */
135
    public function getRequests()
136
    {
137
        return $this->requests;
138
    }
139
140
    public function getLastRequest()
141
    {
142
        return end($this->requests);
143
    }
144
145
    public function reset()
146
    {
147
        $this->responses = [];
148
        $this->exceptions = [];
149
        $this->requests = [];
150
        $this->setDefaultException();
151
        $this->setDefaultResponse();
152
    }
153
}
154