Completed
Push — master ( 939a81...dc41f6 )
by Andy
02:26
created

Curl::postJson()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
ccs 5
cts 6
cp 0.8333
crap 2.0185
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->setUrl($url);
35
36 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...
37 8
        $this->request = new Request();
38
39 8
        $this->buildCurlOpts($curlOpts);
40 8
    }
41
42
    public static function getContents(string $url, array $curlOpts = []): string
43
    {
44
        $curl = new self($url, $curlOpts);
45
46
        return $curl->getResponse()->getBody();
47
    }
48
49
    /**
50
     * @param string|array $data
51
     */
52 2
    public function post($data): Response
53
    {
54 2
        $this->getRequest()->setBody($data);
55
56 2
        return $this->execute();
57
    }
58
59 1
    public function postJson($json): Response
60
    {
61 1
        if (!\is_string($json)) {
62
            $json = \json_encode($json);
63
        }
64
65 1
        $this->getRequest()->addHeader('Content-Type', 'application/json');
66 1
        $this->getRequest()->addHeader('Content-Length', \strlen($json));
67
68 1
        return $this->post($json);
69
    }
70
71 4
    public function execute(): Response
72
    {
73 4
        if ($this->response !== null) {
74 1
            throw new BadMethodCallException('Request has already been executed');
75
        }
76
77 4
        if ($headers = $this->getRequest()->getHeaderStrings()) {
78 1
            \curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
79
        }
80
81 4
        if ($body = $this->getRequest()->getBody()) {
82 2
            \curl_setopt($this->handle, CURLOPT_POST, true);
83 2
            \curl_setopt($this->handle, CURLOPT_POSTFIELDS, $body);
84
        }
85
86 4
        $response   = \curl_exec($this->handle);
87 4
        $statusCode = \curl_getinfo($this->handle, CURLINFO_HTTP_CODE);
88
89 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

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