|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace ThallesDKoester\Entregas; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Thalles D. Koester | Trait Curl |
|
9
|
|
|
* |
|
10
|
|
|
* @author Thalles D. koester <[email protected]> |
|
11
|
|
|
* @package ThallesDKoester\Entregas |
|
12
|
|
|
*/ |
|
13
|
|
|
trait Curl |
|
14
|
|
|
{ |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @param string $path |
|
18
|
|
|
* @param string $method |
|
19
|
|
|
* @param array|null $params |
|
20
|
|
|
* @param int $port |
|
21
|
|
|
* @return string |
|
22
|
|
|
* @throws Exception |
|
23
|
|
|
*/ |
|
24
|
|
|
private function request(string $path, string $method, ?array $params = null, ?int $port = null): string |
|
25
|
|
|
{ |
|
26
|
|
|
$conn = curl_init(); |
|
27
|
|
|
|
|
28
|
|
|
if ($conn === false) { |
|
29
|
|
|
throw new Exception('Erro na inicialízação do cURL.'); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
curl_setopt($conn, CURLOPT_URL, $path); |
|
33
|
|
|
curl_setopt($conn, CURLOPT_TIMEOUT, 30); |
|
34
|
|
|
curl_setopt($conn, CURLOPT_RETURNTRANSFER, true); |
|
35
|
|
|
curl_setopt($conn, CURLOPT_CUSTOMREQUEST, $method); |
|
36
|
|
|
curl_setopt($conn, CURLOPT_FORBID_REUSE, true); |
|
37
|
|
|
curl_setopt($conn, CURLOPT_HTTPHEADER, [ |
|
38
|
|
|
"cache-control: no-cache", |
|
39
|
|
|
"content-type: application/x-www-form-urlencoded" |
|
40
|
|
|
]); |
|
41
|
|
|
|
|
42
|
|
|
if (!empty($params) && count($params) > 0) { |
|
43
|
|
|
curl_setopt($conn, CURLOPT_POSTFIELDS, http_build_query($params)); |
|
44
|
|
|
} else { |
|
45
|
|
|
curl_setopt($conn, CURLOPT_POSTFIELDS, null); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
if ($port) { |
|
|
|
|
|
|
49
|
|
|
curl_setopt($conn, CURLOPT_PORT, $port); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
$data = curl_exec($conn); |
|
53
|
|
|
$err = curl_error($conn); |
|
54
|
|
|
curl_close($conn); |
|
55
|
|
|
|
|
56
|
|
|
if ($err) { |
|
57
|
|
|
throw new Exception($err); |
|
58
|
|
|
} else { |
|
59
|
|
|
return $this->validateData($data); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @param $response |
|
65
|
|
|
* @return string |
|
66
|
|
|
* @throws Exception |
|
67
|
|
|
*/ |
|
68
|
|
|
private function validateData($response): string |
|
69
|
|
|
{ |
|
70
|
|
|
if (empty($response)) { |
|
71
|
|
|
throw new Exception("curl could not reach the server."); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
if (!$response) { |
|
75
|
|
|
throw new Exception($response); |
|
76
|
|
|
} |
|
77
|
|
|
return $response; |
|
78
|
|
|
} |
|
79
|
|
|
} |
In PHP, under loose comparison (like
==, or!=, orswitchconditions), values of different types might be equal.For
integervalues, zero is a special case, in particular the following results might be unexpected: