Request::send()   B
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 13
nc 6
nop 2
1
<?php declare(strict_types=1);
2
3
/**
4
 * @author  Vadim Bova <[email protected]>
5
 * @link    https://bova.io
6
 */
7
8
namespace Folour\Oxide\Components\Request;
9
10
use Folour\Oxide\Exceptions\Exception;
11
use Folour\Oxide\Interfaces\RequestInterface;
12
use Folour\Oxide\Interfaces\ResponseInterface;
13
use Folour\Oxide\Components\Response\Response;
14
15
/**
16
 * @inheritdoc
17
 */
18
class Request implements RequestInterface
19
{
20
    /**
21
     * @var array
22
     */
23
    protected $global_options;
24
25
    /**
26
     * Request constructor
27
     *
28
     * @param array $global_options cURL options
29
     */
30
    public function __construct(array $global_options)
31
    {
32
        $this->global_options = $global_options;
33
    }
34
35
    /**
36
     * Send request
37
     *
38
     * @param string $url
39
     * @param array|null $data
40
     * @return ResponseInterface
41
     * @throws Exception
42
     */
43
    public final function send(string $url, array $data = null): ResponseInterface
0 ignored issues
show
Coding Style introduced by
As per PSR2, final should precede the visibility keyword.
Loading history...
44
    {
45
        if($data !== null) {
46
            $data = $data ? http_build_query($data, '', '&') : null;
47
        }
48
        $options = $this->prepare($url, $data);
49
        $handle  = curl_init();
50
51
        curl_setopt_array($handle, $options);
52
53
        $response   = curl_exec($handle);
54
        $error      = curl_error($handle);
55
        $info       = curl_getinfo($handle);
56
57
        curl_close($handle);
58
59
        if($error !== '') {
60
            throw new Exception('Request failed with error: "'.$error.'"');
61
        }
62
63
        return new Response($response, $info);
64
    }
65
66
    /**
67
     * Prepare request
68
     *
69
     * @param   string  $url
70
     * @param   string  $raw_data
71
     * @return  array
72
     */
73
    protected function prepare(string $url, string $raw_data = null): array
74
    {
75
        //By Default is GET request without query string
76
77
        return array_replace($this->global_options, [
78
            CURLOPT_URL => $url
79
        ]);
80
    }
81
}