diff --git a/README.md b/README.md index d0d370e..80eec4e 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,11 @@ Um exemplo passando opções como o token do CEP Aberto ```php use Prhost\CepGratis\CepGratis; -$address = CepGratis::search('31030080', ['token' => '123abc']); +$cep = '31030080'; +$options = ['token' => '123abc']; +$timeout = 15; //segundos + +$address = CepGratis::search($cep, $options, $timeout); ``` Outras formas: @@ -49,7 +53,7 @@ use Prhost\CepGratis\CepGratis; use Prhost\CepGratis\Providers\CepAbertoProvider; $cepGratis = new CepGratis(); -$cepGratis->setOptions(['token' => 'f944751e6dd14d7a40bf18d4d8df1741']); +$cepGratis->setOptions(['token' => '123abc']); $cepGratis->addProvider(new CepAbertoProvider()); $cepGratis->setTimeout(15); $address = $cepGratis->resolve('31030080'); diff --git a/src/CepGratis.php b/src/CepGratis.php index 3ee7170..8548edc 100644 --- a/src/CepGratis.php +++ b/src/CepGratis.php @@ -29,7 +29,7 @@ class CepGratis private $providers = []; /** - * @var int + * @var int in seconds */ private $timeout = 5; @@ -51,14 +51,16 @@ public function __construct() * * @param string $cep CEP * @param array $options + * @param int $timeout in seconds (optional) * @return Address * @throws CepGratisInvalidParameterException * @throws CepGratisTimeoutException */ - public static function search(string $cep, array $options = []) + public static function search(string $cep, array $options = [], int $timeout = null) { $cepGratis = new self(); $cepGratis->options = $options; + $cepGratis->timeout = $timeout ? $timeout : $cepGratis->timeout; $cepGratis->addProvider(new ViaCepProvider()); $cepGratis->addProvider(new CorreiosProvider()); @@ -81,6 +83,8 @@ public static function search(string $cep, array $options = []) */ public function resolve($cep) { + $cep = $this->clearCep($cep); + if (strlen($cep) != 8 && filter_var($cep, FILTER_VALIDATE_INT) === false) { throw new CepGratisInvalidParameterException('CEP is invalid'); } @@ -97,6 +101,13 @@ public function resolve($cep) do { foreach ($this->providers as $provider) { $address = $provider->getAddress($cep, $this->client, $this->options); + if (!is_null($address)) { + break; + } + } + + if (!is_null($address)) { + break; } if ((time() - $time) >= $this->timeout) { @@ -147,4 +158,15 @@ public function setOptions(array $options): void { $this->options = $options; } + + /** + * Limpa os caracteres especiais do CEP + * + * @param string $cep + * @return string + */ + protected function clearCep(string $cep): string + { + return preg_replace('#[^0-9]#', '', $cep); + } }