Completed
Push — master ( 202c6b...44894d )
by Andy
01:25
created

Curl::buildCurlOpts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 8
rs 10
ccs 4
cts 4
cp 1
crap 1
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 11
    public function __construct(string $url, array $curlOpts = [])
33
    {
34 11
        $this->url     = $url;
35 11
        $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 11
        $this->request = new Request();
37
38 11
        $this->buildCurlOpts($curlOpts);
39 11
    }
40
41 1
    public static function getContents(string $url, array $curlOpts = []): string
42
    {
43 1
        $curl = new self($url, $curlOpts);
44
45 1
        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(string $json): Response
59
    {
60 1
        $this->getRequest()->addHeader('Content-Type', 'application/json');
61 1
        $this->getRequest()->addHeader('Content-Length', \strlen($json));
62
63 1
        return $this->post($json);
64
    }
65
66 6
    public function execute(): Response
67
    {
68 6
        if ($this->response !== null) {
69 1
            throw new BadMethodCallException('Request has already been executed');
70
        }
71
72 6
        if ($headers = $this->getRequest()->getHeaderStrings()) {
73 1
            \curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
74
        }
75
76 6
        if ($body = $this->getRequest()->getBody()) {
77 2
            \curl_setopt($this->handle, CURLOPT_POST, true);
78 2
            \curl_setopt($this->handle, CURLOPT_POSTFIELDS, $body);
79
        }
80
81 6
        $response   = \curl_exec($this->handle);
82 6
        $statusCode = \curl_getinfo($this->handle, CURLINFO_HTTP_CODE);
83
84 6
        $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

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