Completed
Push — master ( 84ca4a...202c6b )
by Andy
02:06 queued 42s
created

Curl::getResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 7
rs 10
ccs 4
cts 4
cp 1
crap 2
1
<?php
2
3
namespace Palmtree\Curl;
4
5
use Palmtree\Curl\Exception\BadMethodCallException;
6
use Palmtree\Curl\Exception\InvalidArgumentException;
7
8
class Curl
9
{
10
    public static $defaultCurlOpts = [
11
        CURLOPT_RETURNTRANSFER => true,
12
        CURLOPT_FOLLOWLOCATION => true,
13
        CURLOPT_AUTOREFERER    => true,
14
        CURLOPT_USERAGENT      => 'Palmtree\Curl',
15
    ];
16
17
    /** @var string */
18
    private $url;
19
    /** @var resource */
20
    private $handle;
21
    /** @var Request */
22
    private $request;
23
    /** @var Response */
24
    private $response;
25
    /** @var array */
26
    private $curlOpts = [];
27
28
    const HTTP_NOT_FOUND = 404;
29
    const HTTP_OK_MIN    = 200;
30
    const HTTP_OK_MAX    = 299;
31
32 8
    public function __construct(string $url, array $curlOpts = [])
33
    {
34 8
        $this->url     = $url;
35 8
        $this->handle  = \curl_init($url);
0 ignored issues
show
Documentation Bug introduced by
It seems like curl_init($url) can also be of type false. However, the property $handle is declared as type resource. 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...
36 8
        $this->request = new Request();
37
38 8
        $this->buildCurlOpts($curlOpts);
39 8
    }
40
41
    public static function getContents(string $url, array $curlOpts = []): string
42
    {
43
        $curl = new self($url, $curlOpts);
44
45
        return $curl->getResponse()->getBody();
46
    }
47
48
    /**
49
     * @param string|array $data
50
     */
51 2
    public function post($data): Response
52
    {
53 2
        $this->getRequest()->setBody($data);
54
55 2
        return $this->execute();
56
    }
57
58 1
    public function postJson($json): Response
59
    {
60 1
        if (!\is_string($json)) {
61
            $json = \json_encode($json);
62
        }
63
64 1
        $this->getRequest()->addHeader('Content-Type', 'application/json');
65 1
        $this->getRequest()->addHeader('Content-Length', \strlen($json));
66
67 1
        return $this->post($json);
68
    }
69
70 4
    public function execute(): Response
71
    {
72 4
        if ($this->response !== null) {
73 1
            throw new BadMethodCallException('Request has already been executed');
74
        }
75
76 4
        if ($headers = $this->getRequest()->getHeaderStrings()) {
77 1
            \curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
78
        }
79
80 4
        if ($body = $this->getRequest()->getBody()) {
81 2
            \curl_setopt($this->handle, CURLOPT_POST, true);
82 2
            \curl_setopt($this->handle, CURLOPT_POSTFIELDS, $body);
83
        }
84
85 4
        $response   = \curl_exec($this->handle);
86 4
        $statusCode = \curl_getinfo($this->handle, CURLINFO_HTTP_CODE);
87
88 4
        $this->response = new Response($response, $statusCode);
0 ignored issues
show
Bug introduced by
It seems like $response can also be of type boolean; however, parameter $response of Palmtree\Curl\Response::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

88
        $this->response = new Response(/** @scrutinizer ignore-type */ $response, $statusCode);
Loading history...
89
90 4
        return $this->response;
91
    }
92
93 4
    public function getRequest(): Request
94
    {
95 4
        return $this->request;
96
    }
97
98 1
    public function getResponse(): Response
99
    {
100 1
        if ($this->response === null) {
101 1
            $this->execute();
102
        }
103
104 1
        return $this->response;
105
    }
106
107 1
    public function getUrl(): string
108
    {
109 1
        return $this->url;
110
    }
111
112 2
    public function getOpts(): array
113
    {
114 2
        return $this->curlOpts;
115
    }
116
117 1
    public function setOpt(int $key, $value): self
118
    {
119 1
        if ($key === CURLOPT_HEADER && !$value) {
120 1
            throw new InvalidArgumentException('CURLOPT_HEADER cannot be set to false');
121
        }
122
123
        $this->curlOpts[$key] = $value;
124
125
        \curl_setopt($this->handle, $key, $value);
126
127
        return $this;
128
    }
129
130
    public function __toString(): string
131
    {
132
        return $this->getResponse()->getBody() ?: '';
133
    }
134
135 8
    private function buildCurlOpts(array $curlOpts)
136
    {
137 8
        $this->curlOpts = \array_replace(self::$defaultCurlOpts, $curlOpts);
138
139
        // The Response class always parses headers.
140 8
        $this->curlOpts[CURLOPT_HEADER] = true;
141
142 8
        \curl_setopt_array($this->handle, $this->curlOpts);
143 8
    }
144
}
145