Completed
Pull Request — master (#4)
by
unknown
02:57
created

Client::getBuzzHeaders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

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 2
eloc 8
nc 2
nop 1
crap 6
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
use InvalidArgumentException;
18
19
/**
20
 * @author Tobias Nyholm <[email protected]>
21
 */
22
class Client implements HttpClient
23
{
24
    /**
25
     * @var ClientInterface
26
     */
27
    private $client;
28
29
    /**
30
     * @var MessageFactory
31
     */
32
    private $messageFactory;
33
34
    /**
35
     * @param ClientInterface|Browser|null $client
36
     * @param MessageFactory|null          $messageFactory
37
     */
38 160
    public function __construct($client = null, MessageFactory $messageFactory = null)
39
    {
40 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...
41
42 160
        if ($this->client === null) {
43 53
            $this->client = new FileGetContents();
44 53
            $this->client->setMaxRedirects(0);
45 54
        }
46
47 160
        if ((!$this->client instanceof ClientInterface) && (!$this->client instanceof Browser)) {
48 1
            throw new InvalidArgumentException(
49 1
                sprintf(
50 1
                    'Buzz adapter client of instance %s must implement %s or be an instance of %s',
51 1
                    get_class($client),
52
                    ClientInterface::class,
53
                    Browser::class
54
                )
55
            );
56
        }
57
58
        $this->messageFactory = $messageFactory ?: MessageFactoryDiscovery::find();
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function sendRequest(RequestInterface $request)
65
    {
66
        $buzzRequest = $this->createRequest($request);
67
68
        try {
69
            $buzzResponse = new BuzzResponse();
70
            $this->client->send($buzzRequest, $buzzResponse);
71
        } catch (BuzzException\ClientException $e) {
72
            throw new HttplugException\TransferException($e->getMessage(), 0, $e);
73
        }
74
75
        return $this->createResponse($buzzResponse);
76
    }
77
78
    /**
79
     * Converts a PSR request into a BuzzRequest request.
80
     *
81
     * @param RequestInterface $request
82
     *
83
     * @return BuzzRequest
84
     */
85
    private function createRequest(RequestInterface $request)
86
    {
87
        $buzzRequest = new BuzzRequest();
88
        $buzzRequest->setMethod($request->getMethod());
89
        $buzzRequest->fromUrl($request->getUri()->__toString());
90
        $buzzRequest->setProtocolVersion($request->getProtocolVersion());
91
        $buzzRequest->setContent((string) $request->getBody());
92
93
        $this->addPsrHeadersToBuzzRequest($request, $buzzRequest);
94
95
        return $buzzRequest;
96
    }
97
98
    /**
99
     * Converts a Buzz response into a PSR response.
100
     *
101
     * @param BuzzResponse $response
102
     *
103
     * @return ResponseInterface
104
     */
105
    private function createResponse(BuzzResponse $response)
106
    {
107
        $body = $response->getContent();
108
109
        return $this->messageFactory->createResponse(
110
            $response->getStatusCode(),
111
            null,
112
            $this->getBuzzHeaders($response),
113
            $body,
114
            number_format($response->getProtocolVersion(), 1)
115
        );
116
    }
117
118
    /**
119
     * Apply headers on a Buzz request.
120
     *
121
     * @param RequestInterface $request
122
     * @param BuzzRequest      $buzzRequest
123
     */
124
    private function addPsrHeadersToBuzzRequest(RequestInterface $request, BuzzRequest $buzzRequest)
125
    {
126
        $headers = $request->getHeaders();
127
        foreach ($headers as $name => $values) {
128
            foreach ($values as $header) {
129
                $buzzRequest->addHeader($name.': '.$header);
130
            }
131
        }
132
    }
133
134
    /**
135
     * Get headers from a Buzz response.
136
     *
137
     * @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...
138
     * @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...
139
     *
140
     * @return array
141
     */
142
    private function getBuzzHeaders(BuzzResponse $response)
143
    {
144
        $buzzHeaders = $response->getHeaders();
145
        unset($buzzHeaders[0]);
146
        $headers = [];
147
        foreach ($buzzHeaders as $headerLine) {
148
            list($name, $value) = explode(':', $headerLine, 2);
149
            $headers[$name] = trim($value);
150
        }
151
152
        return $headers;
153
    }
154
}
155