diff --git a/src/Providers/CorreiosProvider.php b/src/Providers/CorreiosProvider.php index 0254bce..2747234 100644 --- a/src/Providers/CorreiosProvider.php +++ b/src/Providers/CorreiosProvider.php @@ -25,23 +25,47 @@ public function getAddress($cep, HttpClientContract $client, array $option = []) $message = $crawler->filter('div.ctrlcontent p')->html(); - if ($message == 'DADOS ENCONTRADOS COM SUCESSO.') { - $tr = $crawler->filter('table.tmptabela'); + if (!is_null($response)) { + $crawler = new Crawler($response); - $params['zipcode'] = $cep; - $params['street'] = $tr->filter('tr:nth-child(1) td:nth-child(2)')->html(); - $params['neighborhood'] = $tr->filter('tr:nth-child(2) td:nth-child(2)')->html(); + $message = $crawler->filter('div.ctrlcontent p')->html(); - $aux = explode('/', $tr->filter('tr:nth-child(3) td:nth-child(2)')->html()); - $params['city'] = $aux[0]; - $params['state'] = $aux[1]; + if ($message == 'DADOS ENCONTRADOS COM SUCESSO.') { + $tr = $crawler->filter('table.tmptabela'); - $aux = explode(' - ', $params['street']); - $params['street'] = (count($aux) == 2) ? $aux[0] : $params['street']; + $params['zipcode'] = $cep; + $params['street'] = ''; + $params['neighborhood'] = ''; + $params['city'] = ''; + $params['state'] = ''; - return Address::create(array_map(function ($item) { - return urldecode(str_replace('%C2%A0', '', urlencode($item))); - }, $params)); + for ($i = 1; $i <= 3; $i++) { + if ($tr->filter('tr:nth-child('.$i.') th:nth-child(1)')->count() <= 0) { + break; + } + + $index = trim($tr->filter('tr:nth-child('.$i.') th:nth-child(1)')->text(), ':'); + $value = $tr->filter('tr:nth-child('.$i.') td:nth-child(2)')->text(); + switch ($index) { + case 'Logradouro': + $aux = explode(' - ', $value); + $params['street'] = (count($aux) == 2) ? $aux[0] : $value; + break; + case 'Bairro': + $params['neighborhood'] = $value; + break; + case 'Localidade/UF': + $aux = explode('/', $value); + $params['city'] = $aux[0]; + $params['state'] = $aux[1]; + break; + } + } + + return Address::create(array_map(function ($item) { + return urldecode(str_replace('%C2%A0', '', urlencode($item))); + }, $params)); + } } } catch (\Exception $exception) {