|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Wead\ZipCode\WS; |
|
4
|
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
|
6
|
|
|
use Wead\ZipCode\Contracts\ProviderContract; |
|
7
|
|
|
|
|
8
|
|
|
class WebMania extends ProviderContract |
|
9
|
|
|
{ |
|
10
|
|
|
private $endPoint = "https://webmaniabr.com/api/1/cep"; |
|
11
|
|
|
private $apiKey = null; |
|
12
|
|
|
private $apiSecret = null; |
|
13
|
4 |
|
|
|
14
|
|
|
public function __construct($credential = []) |
|
15
|
4 |
|
{ |
|
16
|
4 |
|
if (is_array($credential)) { |
|
17
|
3 |
|
if (isset($credential['apiKey']) && isset($credential['apiSecret'])) { |
|
18
|
3 |
|
$this->apiKey = $credential['apiKey']; |
|
19
|
|
|
$this->apiSecret = $credential['apiSecret']; |
|
20
|
|
|
} |
|
21
|
4 |
|
} |
|
22
|
|
|
} |
|
23
|
3 |
|
|
|
24
|
|
|
public function getAddressFromZipcode($zipCode, $runningTests = false) |
|
25
|
3 |
|
{ |
|
26
|
3 |
|
if (!$this->apiKey || $runningTests) { |
|
27
|
|
|
return $this->normalizeResponse([]); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
$zipCode = preg_replace('/[^0-9]/im', '', $zipCode); |
|
31
|
|
|
|
|
32
|
|
|
$headers = [ |
|
33
|
|
|
"Accept" => "application/json", |
|
34
|
|
|
]; |
|
35
|
|
|
|
|
36
|
|
|
$client = new Client(['base_uri' => "{$this->endPoint}/{$zipCode}/"]); |
|
37
|
|
|
|
|
38
|
|
|
$response = $client->get( |
|
39
|
|
|
'', |
|
40
|
|
|
[ |
|
41
|
|
|
'headers' => $headers, |
|
42
|
|
|
'connect_timeout' => 5, // seconds |
|
43
|
|
|
'query' => [ |
|
44
|
|
|
'app_key' => $this->apiKey, |
|
45
|
|
|
'app_secret' => $this->apiSecret, |
|
46
|
|
|
], |
|
47
|
|
|
'debug' => false, |
|
48
|
|
|
] |
|
49
|
|
|
); |
|
50
|
|
|
|
|
51
|
|
|
$response = $response->getBody()->getContents(); |
|
52
|
|
|
$response = json_decode($response); |
|
53
|
|
|
|
|
54
|
|
|
return $this->normalizeResponse((array)$response); |
|
55
|
|
|
} |
|
56
|
4 |
|
|
|
57
|
|
|
private function normalizeResponse($address) |
|
58
|
4 |
|
{ |
|
59
|
|
|
if (sizeof($address) > 0 && !isset($address["error"])) { |
|
60
|
1 |
|
return [ |
|
61
|
1 |
|
"status" => true, |
|
62
|
1 |
|
"address" => $address["endereco"], |
|
63
|
1 |
|
"district" => $address["bairro"], |
|
64
|
1 |
|
"city" => $address["cidade"], |
|
65
|
1 |
|
"state" => $address["uf"], |
|
66
|
|
|
"api" => "WebMania" |
|
67
|
|
|
]; |
|
68
|
|
|
} else { |
|
69
|
3 |
|
return [ |
|
70
|
|
|
"status" => false, |
|
71
|
|
|
"address" => null, |
|
72
|
|
|
"district" => null, |
|
73
|
|
|
"city" => null, |
|
74
|
|
|
"state" => null, |
|
75
|
|
|
"api" => "WebMania" |
|
76
|
|
|
]; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|