Cep::validate()   A
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 13
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 20
rs 9.2222
1
<?php
2
3
namespace Validate;
4
5
use GuzzleHttp\Client as Http;
6
use Exception;
7
8
class Cep implements \Validate\Contracts\Validate
9
{
10
11
    public static function toDatabase($cep)
12
    {
13
        return preg_replace('/[^0-9]/', '', trim($cep));
14
    }
15
    
16
    public static function toUser($cep)
17
    {
18
        return $cep;
19
    }
20
21
    public static function validate($cep)
22
    {
23
        if (preg_match('/[0-9]{2,2}([.]?)[0-9]{3,3}([- ]?)[0-9]{3}$/', $cep) == 0 ) {            
24
            return false;
25
        }
26
        try {
27
            $client = new Http();
28
            $res = $client->request('GET', 'https://viacep.com.br/ws/'.self::toDatabase($cep).'/json/');
29
            if ($res->getStatusCode() !== 200) {
30
                return false;
31
            }
32
            $json = json_decode($res->getBody());
33
            if (isset($json->error) && $json->error = true) {
34
                return false;
35
            }
36
        } catch (Exception $e) {
37
            return false;
38
        }
39
40
        return true;
41
    }
42
43
    public static function isSame(string $to, string $from)
44
    {
45
        return (self::toDatabase($to)===self::toDatabase($from));
46
    }
47
48
}
49