/
Request.php
112 lines (93 loc) · 2.14 KB
/
Request.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php namespace Vinelab\Http;
use Vinelab\Http\Contracts\RequestInterface;
Class Request implements RequestInterface{
/**
* The default request schema
* @var Array
*/
protected $default = [
'url' => null,
'params' => [],
'headers' => [],
'options' => [],
'returnTransfer' => true,
'json' => false
];
/**
* HTTP Request Method
* @var string
*/
public $method = self::METHOD_GET;
/**
* @var Array
*/
public $params = [];
/**
* @var String
*/
public $url = null;
/**
* Request Headers
* @var Associative Array
*/
public $headers = [];
/**
* Sets the request
* @var boolean
*/
public $json= false;
/**
* Return cURL transfer or not
* @var boolean
*/
public $returnTransfer = true;
/**
* @param Array $requestData
*/
function __construct($requestData)
{
$data = array_merge($this->default, $requestData);
$this->url = $data['url'];
$this->method = $data['method'];
$this->params = $data['params'];
$this->headers = $data['headers'];
$this->json = $data['json'];
if ($this->json)
{
array_push($this->headers, 'Content-Type: application/json');
}
}
public function send()
{
$cURLOptions = array(
CURLOPT_URL => $this->url,
CURLOPT_RETURNTRANSFER => $this->returnTransfer,
CURLOPT_HTTPHEADER => $this->headers,
CURLOPT_HEADER => true,
CURLINFO_HEADER_OUT => true
);
if ($this->method === static::method('POST'))
{
$cURLOptions[CURLOPT_POST] = count($this->params);
$cURLOptions[CURLOPT_POSTFIELDS] = ($this->json) ? json_encode($this->params) : http_build_query($this->params);
} elseif (count($this->params) > 0) {
$this->url = $this->url.'?'.http_build_query($this->params);
$cURLOptions[CURLOPT_URL] = $this->url;
}
// initialize cURL
$cURL = curl_init();
curl_setopt_array($cURL, $cURLOptions);
return Response::make($cURL);
}
/**
* returns the value of an HTTP Verb constant of this class
*
* @param string $method HTTP Verb
* @return string
*/
public static function method($method)
{
$const = 'METHOD_'.strtoupper($method);
return constant('self::'.$const);
}
}