Completed
Pull Request — master (#4)
by
unknown
04:12
created

Client::addPsrHeadersToBuzzRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 0
cp 0
rs 9.6666
cc 3
eloc 5
nc 3
nop 2
crap 12
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 161
    public function __construct($client = null, MessageFactory $messageFactory = null)
38
    {
39 161
        $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 161
        if ($this->client === null) {
42 53
            $this->client = new FileGetContents();
43 53
            $this->client->setMaxRedirects(0);
44 53
        }
45
46 161
        if ((!$this->client instanceof ClientInterface) && (!$this->client instanceof Browser)) {
47 2
            throw new \InvalidArgumentException(
48 2
                sprintf(
49 2
                    'The client passed to the Buzz adapter must either implement %s or be an instance of %s. You passed %s.',
50
                    ClientInterface::class,
51
                    Browser::class,
52
                    is_object($client) ? get_class($client) : gettype($client)
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 BuzzResponse $response
137
     *
138
     * @return array
139
     */
140
    private function getBuzzHeaders(BuzzResponse $response)
141
    {
142
        $buzzHeaders = $response->getHeaders();
143
        unset($buzzHeaders[0]);
144
        $headers = [];
145
        foreach ($buzzHeaders as $headerLine) {
146
            list($name, $value) = explode(':', $headerLine, 2);
147
            $headers[$name] = trim($value);
148
        }
149
150
        return $headers;
151
    }
152
}
153