Completed
Pull Request — master (#4)
by
unknown
03:28
created

Client::createRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
ccs 0
cts 0
cp 0
rs 9.4285
cc 1
eloc 8
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Http\Adapter\Buzz;
4
5
use Buzz\Browser;
6
use Buzz\Client\ClientInterface;
7
use Buzz\Client\FileGetContents;
8
use Buzz\Exception as BuzzException;
9
use Buzz\Message\Request as BuzzRequest;
10
use Buzz\Message\Response as BuzzResponse;
11
use Http\Client\HttpClient;
12
use Http\Discovery\MessageFactoryDiscovery;
13
use Http\Message\MessageFactory;
14
use Psr\Http\Message\RequestInterface;
15
use Psr\Http\Message\ResponseInterface;
16
use Http\Client\Exception as HttplugException;
17
18
/**
19
 * @author Tobias Nyholm <[email protected]>
20
 */
21
class Client implements HttpClient
22
{
23
    /**
24
     * @var ClientInterface
25
     */
26
    private $client;
27
28
    /**
29
     * @var MessageFactory
30
     */
31
    private $messageFactory;
32
33
    /**
34
     * @param ClientInterface|Browser|null $client
35
     * @param MessageFactory|null          $messageFactory
36
     */
37 160
    public function __construct($client = null, MessageFactory $messageFactory = null)
38
    {
39 160
        $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...
40
41 160
        if ($this->client === null) {
42 53
            $this->client = new FileGetContents();
43 53
            $this->client->setMaxRedirects(0);
44 53
        }
45
46 160
        if ((!$this->client instanceof ClientInterface) && (!$this->client instanceof Browser)) {
47 1
            throw new \InvalidArgumentException(
48 1
                sprintf(
49 1
                    'Buzz adapter client of instance %s must implement %s or be an instance of %s',
50 1
                    get_class($client),
51
                    ClientInterface::class,
52
                    Browser::class
53
                )
54
            );
55
        }
56
57
        $this->messageFactory = $messageFactory ?: MessageFactoryDiscovery::find();
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function sendRequest(RequestInterface $request)
64
    {
65
        $buzzRequest = $this->createRequest($request);
66
67
        try {
68
            $buzzResponse = new BuzzResponse();
69
            $this->client->send($buzzRequest, $buzzResponse);
70
        } catch (BuzzException\ClientException $e) {
71
            throw new HttplugException\TransferException($e->getMessage(), 0, $e);
72
        }
73
74
        return $this->createResponse($buzzResponse);
75
    }
76
77
    /**
78
     * Converts a PSR request into a BuzzRequest request.
79
     *
80
     * @param RequestInterface $request
81
     *
82
     * @return BuzzRequest
83
     */
84
    private function createRequest(RequestInterface $request)
85
    {
86
        $buzzRequest = new BuzzRequest();
87
        $buzzRequest->setMethod($request->getMethod());
88
        $buzzRequest->fromUrl($request->getUri()->__toString());
89
        $buzzRequest->setProtocolVersion($request->getProtocolVersion());
90
        $buzzRequest->setContent((string) $request->getBody());
91
92
        $this->addPsrHeadersToBuzzRequest($request, $buzzRequest);
93
94
        return $buzzRequest;
95
    }
96
97
    /**
98
     * Converts a Buzz response into a PSR response.
99
     *
100
     * @param BuzzResponse $response
101
     *
102
     * @return ResponseInterface
103
     */
104
    private function createResponse(BuzzResponse $response)
105
    {
106
        $body = $response->getContent();
107
108
        return $this->messageFactory->createResponse(
109
            $response->getStatusCode(),
110
            null,
111
            $this->getBuzzHeaders($response),
112
            $body,
113
            number_format($response->getProtocolVersion(), 1)
114
        );
115
    }
116
117
    /**
118
     * Apply headers on a Buzz request.
119
     *
120
     * @param RequestInterface $request
121
     * @param BuzzRequest      $buzzRequest
122
     */
123
    private function addPsrHeadersToBuzzRequest(RequestInterface $request, BuzzRequest $buzzRequest)
124
    {
125
        $headers = $request->getHeaders();
126
        foreach ($headers as $name => $values) {
127
            foreach ($values as $header) {
128
                $buzzRequest->addHeader($name.': '.$header);
129
            }
130
        }
131
    }
132
133
    /**
134
     * Get headers from a Buzz response.
135
     *
136
     * @param RequestInterface $request
0 ignored issues
show
Bug introduced by
There is no parameter named $request. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
137
     * @param BuzzRequest      $buzzRequest
0 ignored issues
show
Bug introduced by
There is no parameter named $buzzRequest. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
138
     *
139
     * @return array
140
     */
141
    private function getBuzzHeaders(BuzzResponse $response)
142
    {
143
        $buzzHeaders = $response->getHeaders();
144
        unset($buzzHeaders[0]);
145
        $headers = [];
146
        foreach ($buzzHeaders as $headerLine) {
147
            list($name, $value) = explode(':', $headerLine, 2);
148
            $headers[$name] = trim($value);
149
        }
150
151
        return $headers;
152
    }
153
}
154