Completed
Push — master ( a9fd8c...4b1310 )
by David
8s
created

Client::__construct()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 22
ccs 10
cts 10
cp 1
rs 8.6737
cc 6
eloc 13
nc 6
nop 2
crap 6
1
<?php
2
3
namespace Http\Adapter\Buzz;
4
5
use Buzz\Browser;
6
use Buzz\Client\ClientInterface;
7
use Buzz\Client\Curl;
8
use Buzz\Client\FileGetContents;
9
use Buzz\Exception as BuzzException;
10
use Buzz\Message\Request as BuzzRequest;
11
use Buzz\Message\RequestInterface as BuzzRequestInterface;
12
use Buzz\Message\Response as BuzzResponse;
13
use Http\Client\HttpClient;
14
use Http\Discovery\MessageFactoryDiscovery;
15
use Http\Message\MessageFactory;
16
use Psr\Http\Message\RequestInterface;
17
use Psr\Http\Message\ResponseInterface;
18
use Http\Client\Exception as HttplugException;
19
20
/**
21
 * @author Tobias Nyholm <[email protected]>
22
 */
23
class Client implements HttpClient
24
{
25
    /**
26
     * @var ClientInterface
27
     */
28
    private $client;
29
30
    /**
31
     * @var MessageFactory
32
     */
33
    private $messageFactory;
34
35
    /**
36
     * @param ClientInterface|Browser|null $client
37
     * @param MessageFactory|null          $messageFactory
38
     */
39 214
    public function __construct($client = null, MessageFactory $messageFactory = null)
40
    {
41 214
        $this->client = $client;
0 ignored issues
show
Documentation Bug introduced by
It seems like $client can also be of type object<Buzz\Browser>. However, the property $client is declared as type object<Buzz\Client\ClientInterface>. 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...
42
43 214
        if ($this->client === null) {
44 53
            $this->client = new FileGetContents();
45 54
            $this->client->setMaxRedirects(0);
46 53
        }
47
48 214
        if ((!$this->client instanceof ClientInterface) && (!$this->client instanceof Browser)) {
49 2
            throw new \InvalidArgumentException(
50 2
                sprintf(
51 2
                    'The client passed to the Buzz adapter must either implement %s or be an instance of %s. You passed %s.',
52
                    ClientInterface::class,
53
                    Browser::class,
54
                    is_object($client) ? get_class($client) : gettype($client)
55
                )
56
            );
57
        }
58
59
        $this->messageFactory = $messageFactory ?: MessageFactoryDiscovery::find();
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function sendRequest(RequestInterface $request)
66
    {
67
        $this->assertRequestHasValidBody($request);
68
69
        $buzzRequest = $this->createRequest($request);
70
71
        try {
72
            $buzzResponse = new BuzzResponse();
73
            $this->client->send($buzzRequest, $buzzResponse);
74
        } catch (BuzzException\ClientException $e) {
75
            throw new HttplugException\TransferException($e->getMessage(), 0, $e);
76
        }
77
78
        return $this->createResponse($buzzResponse);
79
    }
80
81
    /**
82
     * Converts a PSR request into a BuzzRequest request.
83
     *
84
     * @param RequestInterface $request
85
     *
86
     * @return BuzzRequest
87
     */
88
    private function createRequest(RequestInterface $request)
89
    {
90
        $buzzRequest = new BuzzRequest();
91
        $buzzRequest->setMethod($request->getMethod());
92
        $buzzRequest->fromUrl($request->getUri()->__toString());
93
        $buzzRequest->setProtocolVersion($request->getProtocolVersion());
94
        $buzzRequest->setContent((string) $request->getBody());
95
96
        $this->addPsrHeadersToBuzzRequest($request, $buzzRequest);
97
98
        return $buzzRequest;
99
    }
100
101
    /**
102
     * Converts a Buzz response into a PSR response.
103
     *
104
     * @param BuzzResponse $response
105
     *
106
     * @return ResponseInterface
107
     */
108
    private function createResponse(BuzzResponse $response)
109
    {
110
        $body = $response->getContent();
111
112
        return $this->messageFactory->createResponse(
113
            $response->getStatusCode(),
114
            null,
115
            $this->getBuzzHeaders($response),
116
            $body,
117
            number_format($response->getProtocolVersion(), 1)
118
        );
119
    }
120
121
    /**
122
     * Apply headers on a Buzz request.
123
     *
124
     * @param RequestInterface $request
125
     * @param BuzzRequest      $buzzRequest
126
     */
127
    private function addPsrHeadersToBuzzRequest(RequestInterface $request, BuzzRequest $buzzRequest)
128
    {
129
        $headers = $request->getHeaders();
130
        foreach ($headers as $name => $values) {
131
            foreach ($values as $header) {
132
                $buzzRequest->addHeader($name.': '.$header);
133
            }
134
        }
135
    }
136
137
    /**
138
     * Get headers from a Buzz response.
139
     *
140
     * @param BuzzResponse $response
141
     *
142
     * @return array
143
     */
144
    private function getBuzzHeaders(BuzzResponse $response)
145
    {
146
        $buzzHeaders = $response->getHeaders();
147
        unset($buzzHeaders[0]);
148
        $headers = [];
149
        foreach ($buzzHeaders as $headerLine) {
150
            list($name, $value) = explode(':', $headerLine, 2);
151
            $headers[$name] = trim($value);
152
        }
153
154
        return $headers;
155
    }
156
157
    /**
158
     * Assert that the request has a valid body based on the request method.
159
     *
160
     * @param RequestInterface $request
161
     */
162
    private function assertRequestHasValidBody(RequestInterface $request)
163
    {
164
        $validMethods = [
165
            BuzzRequestInterface::METHOD_POST,
166
            BuzzRequestInterface::METHOD_PUT,
167
            BuzzRequestInterface::METHOD_DELETE,
168
            BuzzRequestInterface::METHOD_PATCH,
169
            BuzzRequestInterface::METHOD_OPTIONS,
170
        ];
171
172
        // The Buzz Curl client does not send request bodies for request methods such as GET, HEAD and TRACE. Instead of
173
        // silently ignoring the request body in these cases, throw an exception to make users aware.
174
        if ($this->client instanceof Curl &&
175
            $request->getBody()->getSize() &&
0 ignored issues
show
Bug Best Practice introduced by
The expression $request->getBody()->getSize() of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
176
            !in_array(strtoupper($request->getMethod()), $validMethods, true)
177
        ) {
178
            throw new \InvalidArgumentException(
179
                sprintf('%s does not support %s requests with a body', Curl::class, $request->getMethod())
180
            );
181
        }
182
    }
183
}
184