@@ -29,7 +29,7 @@ class CepGratis
2929 private $ providers = [];
3030
3131 /**
32- * @var int
32+ * @var int in seconds
3333 */
3434 private $ timeout = 5 ;
3535
@@ -51,14 +51,16 @@ public function __construct()
5151 *
5252 * @param string $cep CEP
5353 * @param array $options
54+ * @param int $timeout in seconds (optional)
5455 * @return Address
5556 * @throws CepGratisInvalidParameterException
5657 * @throws CepGratisTimeoutException
5758 */
58- public static function search (string $ cep , array $ options = [])
59+ public static function search (string $ cep , array $ options = [], int $ timeout = null )
5960 {
6061 $ cepGratis = new self ();
6162 $ cepGratis ->options = $ options ;
63+ $ cepGratis ->timeout = $ timeout ? $ timeout : $ cepGratis ->timeout ;
6264
6365 $ cepGratis ->addProvider (new ViaCepProvider ());
6466 $ cepGratis ->addProvider (new CorreiosProvider ());
@@ -81,6 +83,8 @@ public static function search(string $cep, array $options = [])
8183 */
8284 public function resolve ($ cep )
8385 {
86+ $ cep = $ this ->clearCep ($ cep );
87+
8488 if (strlen ($ cep ) != 8 && filter_var ($ cep , FILTER_VALIDATE_INT ) === false ) {
8589 throw new CepGratisInvalidParameterException ('CEP is invalid ' );
8690 }
@@ -97,6 +101,13 @@ public function resolve($cep)
97101 do {
98102 foreach ($ this ->providers as $ provider ) {
99103 $ address = $ provider ->getAddress ($ cep , $ this ->client , $ this ->options );
104+ if (!is_null ($ address )) {
105+ break ;
106+ }
107+ }
108+
109+ if (!is_null ($ address )) {
110+ break ;
100111 }
101112
102113 if ((time () - $ time ) >= $ this ->timeout ) {
@@ -147,4 +158,15 @@ public function setOptions(array $options): void
147158 {
148159 $ this ->options = $ options ;
149160 }
161+
162+ /**
163+ * Limpa os caracteres especiais do CEP
164+ *
165+ * @param string $cep
166+ * @return string
167+ */
168+ protected function clearCep (string $ cep ): string
169+ {
170+ return preg_replace ('#[^0-9]# ' , '' , $ cep );
171+ }
150172}
0 commit comments