Test Failed
Push — master ( dc41f6...84ca4a )
by Andy
01:30
created

Curl::getContents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 5
rs 10
ccs 0
cts 3
cp 0
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 2
    public function __construct(string $url, array $curlOpts = [])
33
    {
34 2
        $this->setUrl($url);
0 ignored issues
show
Bug introduced by
The method setUrl() does not exist on Palmtree\Curl\Curl. ( Ignorable by Annotation )

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

34
        $this->/** @scrutinizer ignore-call */ 
35
               setUrl($url);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
35
36
        $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
        $this->request = new Request();
38
39
        $this->buildCurlOpts($curlOpts);
40
    }
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
    public function post($data): Response
53
    {
54
        $this->getRequest()->setBody($data);
55
56
        return $this->execute();
57
    }
58
59
    public function postJson($json): Response
60
    {
61
        if (!\is_string($json)) {
62
            $json = \json_encode($json);
63
        }
64
65
        $this->getRequest()->addHeader('Content-Type', 'application/json');
66
        $this->getRequest()->addHeader('Content-Length', \strlen($json));
67
68
        return $this->post($json);
69
    }
70
71
    public function execute(): Response
72
    {
73
        if ($this->response !== null) {
74
            throw new BadMethodCallException('Request has already been executed');
75
        }
76
77
        if ($headers = $this->getRequest()->getHeaderStrings()) {
78
            \curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
79
        }
80
81
        if ($body = $this->getRequest()->getBody()) {
82
            \curl_setopt($this->handle, CURLOPT_POST, true);
83
            \curl_setopt($this->handle, CURLOPT_POSTFIELDS, $body);
84
        }
85
86
        $response   = \curl_exec($this->handle);
87
        $statusCode = \curl_getinfo($this->handle, CURLINFO_HTTP_CODE);
88
89
        $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
        return $this->response;
92
    }
93
94
    public function getRequest(): Request
95
    {
96
        return $this->request;
97
    }
98
99
    public function getResponse(): Response
100
    {
101
        if ($this->response === null) {
102
            $this->execute();
103
        }
104
105
        return $this->response;
106
    }
107
108
    public function getUrl(): string
109
    {
110
        return $this->url;
111
    }
112
113
    public function getOpts(): array
114
    {
115
        return $this->curlOpts;
116
    }
117
118
    public function setOpt(int $key, $value): self
119
    {
120
        if ($key === CURLOPT_HEADER && !$value) {
121
            throw new InvalidArgumentException('CURLOPT_HEADER cannot be set to false');
122
        }
123
124
        $this->curlOpts[$key] = $value;
125
126
        \curl_setopt($this->handle, $key, $value);
127
128
        return $this;
129
    }
130
131
    public function __toString(): string
132
    {
133
        return $this->getResponse()->getBody() ?: '';
134
    }
135
136
    private function buildCurlOpts(array $curlOpts)
137
    {
138
        $this->curlOpts = \array_replace(self::$defaultCurlOpts, $curlOpts);
139
140
        // The Response class always parses headers.
141
        $this->curlOpts[CURLOPT_HEADER] = true;
142
143
        \curl_setopt_array($this->handle, $this->curlOpts);
144
    }
145
}
146