1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ittoolspl\Smslabs; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
6
|
|
|
use Ittoolspl\Smslabs\Exception\InvalidResponseException; |
7
|
|
|
|
8
|
|
|
class HttpClient |
9
|
|
|
{ |
10
|
|
|
const API_URL = 'https://api.smslabs.net.pl/apiSms'; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @var string |
14
|
|
|
*/ |
15
|
|
|
private $appKey = null; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var string |
19
|
|
|
*/ |
20
|
|
|
private $secretKey = null; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var Client |
24
|
|
|
*/ |
25
|
|
|
private $client = null; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* HttpClient constructor. |
29
|
|
|
* @param string $appKey |
30
|
|
|
* @param string $secretKey |
31
|
|
|
*/ |
32
|
|
|
public function __construct($appKey, $secretKey) |
33
|
|
|
{ |
34
|
|
|
$this->appKey = $appKey; |
35
|
|
|
$this->secretKey = $secretKey; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param string $url |
40
|
|
|
* @param array $data |
41
|
|
|
* @param string $method |
42
|
|
|
* @return \stdClass |
43
|
|
|
* @throws InvalidResponseException |
44
|
|
|
*/ |
45
|
|
|
public function sendRequest($url, $data = null, $method = 'GET') |
46
|
|
|
{ |
47
|
|
|
$this->validateMethod($method); |
48
|
|
|
|
49
|
|
|
$response = $this->getClient()->request($method, self::API_URL.$url, [ |
50
|
|
|
'auth' => [$this->appKey, $this->secretKey], |
51
|
|
|
'form_params' => $data, |
52
|
|
|
]); |
53
|
|
|
|
54
|
|
|
if ($response->getStatusCode() != 200) { |
55
|
|
|
throw new InvalidResponseException(); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$bodyJson = (string)$response->getBody(); |
59
|
|
|
|
60
|
|
|
$bodyObj = \GuzzleHttp\json_decode($bodyJson); |
61
|
|
|
|
62
|
|
|
if (!property_exists($bodyObj, 'data')) { |
63
|
|
|
throw new InvalidResponseException('Missing data property in response'); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $bodyObj->data; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
private function validateMethod($method) |
70
|
|
|
{ |
71
|
|
|
if (!in_array($method, ['POST', 'PUT', 'GET', 'DELETE'])) { |
72
|
|
|
throw new \InvalidArgumentException('Invalid method'); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return true; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @return Client |
80
|
|
|
*/ |
81
|
|
|
public function getClient() |
82
|
|
|
{ |
83
|
|
|
if ($this->client === null) { |
84
|
|
|
$this->client = new Client(); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
return $this->client; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* @param Client $client |
92
|
|
|
*/ |
93
|
|
|
public function setClient($client) |
94
|
|
|
{ |
95
|
|
|
$this->client = $client; |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|