ViaCep::getAddressFromZipcode()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 12
nc 1
nop 1
dl 0
loc 23
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
namespace Wead\ZipCode\WS;
4
5
use GuzzleHttp\Client;
6
use Wead\ZipCode\Contracts\ProviderContract;
7
8
class ViaCep extends ProviderContract
9
{
10
    private $endPoint = "https://viacep.com.br/ws/";
11 4
12
    public function getAddressFromZipcode($zipCode)
13 4
    {
14
        $zipCode = preg_replace('/[^0-9]/im', '', $zipCode);
15
16 4
        $headers = [
17
            "Accept" => "application/json",
18
        ];
19 4
20
        $client = new Client(['base_uri' => "{$this->endPoint}/{$zipCode}/"]);
21 4
22 4
        $response = $client->get(
23
            'json',
24 4
            [
25 4
                'headers' => $headers,
26
                'connect_timeout' => 5, // seconds
27
                'debug' => false,
28
                ]
29
        );
30 4
31 4
        $response = $response->getBody()->getContents();
32
        $response = json_decode($response);
33 4
34
        return $this->normalizeResponse((array)$response);
35
    }
36 5
37
    private function normalizeResponse($address)
38 5
    {
39
        if (sizeof($address) > 0 && !isset($address["erro"])) {
40 4
            return [
41 4
                "status" => true,
42 4
                "address" => $address["logradouro"],
43 4
                "district" => $address["bairro"],
44 4
                "city" => $address["localidade"],
45 4
                "state" => $address["uf"],
46
                "api" => "ViaCep"
47
            ];
48
        } else {
49 1
            return [
50
                "status" => false,
51
                "address" => null,
52
                "district" => null,
53
                "city" => null,
54
                "state" => null,
55
                "api" => "ViaCep"
56
            ];
57
        }
58
    }
59
}
60