From b363f7a346f3b97e4d31b8e1d243bae45767caa2 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Sun, 18 Aug 2019 12:43:20 -0300 Subject: [PATCH 1/3] =?UTF-8?q?Refatora=C3=A7=C3=B5es=20simples=20para=20m?= =?UTF-8?q?elhor=20legibilidade?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Address.php | 7 +- src/CepPromise.php | 133 +++++++++++++++------------- src/Contracts/BaseProvider.php | 5 +- src/Contracts/ProviderInterface.php | 4 +- 4 files changed, 84 insertions(+), 65 deletions(-) diff --git a/src/Address.php b/src/Address.php index 8ad510f..ff2e3be 100644 --- a/src/Address.php +++ b/src/Address.php @@ -49,7 +49,7 @@ class Address * * @param array $data * - * @return \Claudsonm\CepPromise\Address + * @return Address */ public static function create(array $data = []) { @@ -61,6 +61,11 @@ public static function create(array $data = []) return $address; } + /** + * Converte a instância da classe em um array associativo. + * + * @return array + */ public function toArray() { return (array) $this; diff --git a/src/CepPromise.php b/src/CepPromise.php index 8c25e3d..3125a98 100644 --- a/src/CepPromise.php +++ b/src/CepPromise.php @@ -2,13 +2,13 @@ namespace Claudsonm\CepPromise; -use Claudsonm\CepPromise\Exceptions\CepPromiseException; -use Claudsonm\CepPromise\Providers\CepAbertoProvider; -use Claudsonm\CepPromise\Providers\CorreiosProvider; -use Claudsonm\CepPromise\Providers\ViaCepProvider; use Exception; use GuzzleHttp\Promise; use GuzzleHttp\Promise\FulfilledPromise; +use Claudsonm\CepPromise\Providers\ViaCepProvider; +use Claudsonm\CepPromise\Providers\CorreiosProvider; +use Claudsonm\CepPromise\Providers\CepAbertoProvider; +use Claudsonm\CepPromise\Exceptions\CepPromiseException; /** * Classe responsável por receber o CEP e disparar as requisições aos providers. @@ -24,15 +24,26 @@ class CepPromise const ERROR_VALIDATION_CODE = 1; /** - * Normaliza o CEP dado e efetua as requisições. + * Dispara a cadeia de execução para obtenção das informações do CEP dado. * * @param $cepRawValue * - * @throws \Claudsonm\CepPromise\Exceptions\CepPromiseException + * @throws CepPromiseException * - * @return \Claudsonm\CepPromise\Address + * @return Address */ public static function fetch($cepRawValue) + { + return (new self())->run($cepRawValue); + } + + /** + * Define o encadeamento das promises. + * + * @param $cepRawValue + * @return Address + */ + public function run($cepRawValue): Address { $promise = new FulfilledPromise($cepRawValue); $cepData = $promise @@ -48,60 +59,34 @@ public static function fetch($cepRawValue) return Address::create($cepData); } - private static function fetchCepFromProviders() - { - return function (string $cepWithLeftPad) { - $promises = array_merge( - ViaCepProvider::createPromiseArray($cepWithLeftPad), - CepAbertoProvider::createPromiseArray($cepWithLeftPad), - CorreiosProvider::createPromiseArray($cepWithLeftPad) - ); - - return Promise\any($promises); - }; - } - - private static function handleProvidersError() + private function validateInputType() { - return function (Exception $onRejected) { - if ($onRejected instanceof Promise\AggregateException) { - throw new CepPromiseException( - 'Todos os serviços de CEP retornaram erro.', - self::ERROR_PROVIDER_CODE, - $onRejected->getReason() - ); + return function ($cepRawValue) { + if (is_string($cepRawValue) || is_int($cepRawValue)) { + return $cepRawValue; } - throw $onRejected; - }; - } - - private static function leftPadWithZeros() - { - return function (string $cepCleanValue) { - return str_pad($cepCleanValue, self::CEP_SIZE, '0', STR_PAD_LEFT); + throw new CepPromiseException( + 'Erro ao inicializar a instância do CepPromise.', + self::ERROR_VALIDATION_CODE, + [ + [ + 'message' => 'Você deve informar o CEP utilizando uma string ou um inteiro.', + 'service' => 'cep_validation', + ], + ] + ); }; } - private static function removeSpecialCharacters() + private function removeSpecialCharacters() { return function (string $cepRawValue) { return preg_replace('/\D+/', '', $cepRawValue); }; } - private static function throwApplicationError() - { - return function (Exception $exception) { - throw new CepPromiseException( - $exception->getMessage(), - $exception->getCode(), - $exception->getErrors() ?? [] - ); - }; - } - - private static function validateInputLength() + private function validateInputLength() { return function (string $cepNumbers) { if (strlen($cepNumbers) <= self::CEP_SIZE) { @@ -121,22 +106,48 @@ private static function validateInputLength() }; } - private static function validateInputType() + private function leftPadWithZeros() { - return function ($cepRawValue) { - if (is_string($cepRawValue) || is_int($cepRawValue)) { - return $cepRawValue; + return function (string $cepCleanValue) { + return str_pad($cepCleanValue, self::CEP_SIZE, '0', STR_PAD_LEFT); + }; + } + + private function fetchCepFromProviders() + { + return function (string $cepWithLeftPad) { + $promises = array_merge( + ViaCepProvider::createPromiseArray($cepWithLeftPad), + CepAbertoProvider::createPromiseArray($cepWithLeftPad), + CorreiosProvider::createPromiseArray($cepWithLeftPad) + ); + + return Promise\any($promises); + }; + } + + private function handleProvidersError() + { + return function (Exception $onRejected) { + if ($onRejected instanceof Promise\AggregateException) { + throw new CepPromiseException( + 'Todos os serviços de CEP retornaram erro.', + self::ERROR_PROVIDER_CODE, + $onRejected->getReason() + ); } + throw $onRejected; + }; + } + + private function throwApplicationError() + { + return function (Exception $exception) { throw new CepPromiseException( - 'Erro ao inicializar a instância do CepPromise.', - self::ERROR_VALIDATION_CODE, - [ - [ - 'message' => 'Você deve informar o CEP utilizando uma string ou um inteiro.', - 'service' => 'cep_validation', - ], - ] + $exception->getMessage(), + $exception->getCode(), + $exception->getErrors() ?? [] ); }; } diff --git a/src/Contracts/BaseProvider.php b/src/Contracts/BaseProvider.php index cb4cde6..aba2a9b 100644 --- a/src/Contracts/BaseProvider.php +++ b/src/Contracts/BaseProvider.php @@ -3,6 +3,7 @@ namespace Claudsonm\CepPromise\Contracts; use GuzzleHttp\Client; +use GuzzleHttp\Promise\Promise; abstract class BaseProvider implements ProviderInterface { @@ -16,14 +17,14 @@ abstract class BaseProvider implements ProviderInterface /** * O cliente HTTP utilizado para realizar os requests. * - * @var \GuzzleHttp\Client + * @var Client */ protected $client; /** * A instância da Promise para consulta no serviço de busca. * - * @var \GuzzleHttp\Promise\Promise + * @var Promise */ protected $promise; diff --git a/src/Contracts/ProviderInterface.php b/src/Contracts/ProviderInterface.php index b5b1051..741ecd4 100644 --- a/src/Contracts/ProviderInterface.php +++ b/src/Contracts/ProviderInterface.php @@ -2,6 +2,8 @@ namespace Claudsonm\CepPromise\Contracts; +use GuzzleHttp\Promise\Promise; + interface ProviderInterface { /** @@ -9,7 +11,7 @@ interface ProviderInterface * * @param string $cep * - * @return \GuzzleHttp\Promise\Promise + * @return Promise */ public function makePromise(string $cep); } From 2d3e5d9f3c4fb1fa15ac5ccddfe8182c09909b1e Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Sat, 14 Sep 2019 01:06:42 -0300 Subject: [PATCH 2/3] =?UTF-8?q?Refatora=C3=A7oes=20para=20melhor=20legibil?= =?UTF-8?q?idade=20e=20testes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 1 + src/CepPromise.php | 23 ++++++------ src/Providers/CepAbertoProvider.php | 6 +-- src/Providers/CorreiosProvider.php | 6 +-- src/Providers/ViaCepProvider.php | 6 +-- tests/Feature/CepPromiseFeatureTest.php | 40 +++++--------------- tests/Unit/CepPromiseUnitTest.php | 50 ++++++++++++++++++++++++- 7 files changed, 78 insertions(+), 54 deletions(-) diff --git a/composer.json b/composer.json index 3ddfbc0..5558974 100644 --- a/composer.json +++ b/composer.json @@ -11,6 +11,7 @@ } ], "require": { + "php": "^7.0", "guzzlehttp/guzzle": "~6.0", "ext-simplexml": "*", "ext-json": "*" diff --git a/src/CepPromise.php b/src/CepPromise.php index 3125a98..a3f87d9 100644 --- a/src/CepPromise.php +++ b/src/CepPromise.php @@ -11,7 +11,8 @@ use Claudsonm\CepPromise\Exceptions\CepPromiseException; /** - * Classe responsável por receber o CEP e disparar as requisições aos providers. + * Efetua a consulta pelas informações de um CEP em diferentes serviços de + * forma concorrente, retornando a resposta mais rápida.. * * @author Claudson Martins */ @@ -24,23 +25,21 @@ class CepPromise const ERROR_VALIDATION_CODE = 1; /** - * Dispara a cadeia de execução para obtenção das informações do CEP dado. - * - * @param $cepRawValue - * - * @throws CepPromiseException + * Busca as informações referente ao CEP informado. * + * @param string|int $cep * @return Address + * @throws CepPromiseException */ - public static function fetch($cepRawValue) + public static function fetch($cep) { - return (new self())->run($cepRawValue); + return (new self())->run($cep); } /** - * Define o encadeamento das promises. + * Dispara a cadeia de execução para obtenção das informações do CEP dado. * - * @param $cepRawValue + * @param string|int $cepRawValue * @return Address */ public function run($cepRawValue): Address @@ -108,8 +107,8 @@ private function validateInputLength() private function leftPadWithZeros() { - return function (string $cepCleanValue) { - return str_pad($cepCleanValue, self::CEP_SIZE, '0', STR_PAD_LEFT); + return function (string $cepSanitized) { + return str_pad($cepSanitized, self::CEP_SIZE, '0', STR_PAD_LEFT); }; } diff --git a/src/Providers/CepAbertoProvider.php b/src/Providers/CepAbertoProvider.php index 4321d1f..9f4e792 100644 --- a/src/Providers/CepAbertoProvider.php +++ b/src/Providers/CepAbertoProvider.php @@ -2,11 +2,11 @@ namespace Claudsonm\CepPromise\Providers; -use Claudsonm\CepPromise\Contracts\BaseProvider; -use Claudsonm\CepPromise\Exceptions\CepPromiseProviderException; use Exception; -use GuzzleHttp\Exception\RequestException; use Psr\Http\Message\ResponseInterface; +use GuzzleHttp\Exception\RequestException; +use Claudsonm\CepPromise\Contracts\BaseProvider; +use Claudsonm\CepPromise\Exceptions\CepPromiseProviderException; class CepAbertoProvider extends BaseProvider { diff --git a/src/Providers/CorreiosProvider.php b/src/Providers/CorreiosProvider.php index e3d17aa..18aad5b 100644 --- a/src/Providers/CorreiosProvider.php +++ b/src/Providers/CorreiosProvider.php @@ -2,11 +2,11 @@ namespace Claudsonm\CepPromise\Providers; -use Claudsonm\CepPromise\Contracts\BaseProvider; -use Claudsonm\CepPromise\Exceptions\CepPromiseProviderException; use Exception; -use GuzzleHttp\Exception\RequestException; use Psr\Http\Message\ResponseInterface; +use GuzzleHttp\Exception\RequestException; +use Claudsonm\CepPromise\Contracts\BaseProvider; +use Claudsonm\CepPromise\Exceptions\CepPromiseProviderException; class CorreiosProvider extends BaseProvider { diff --git a/src/Providers/ViaCepProvider.php b/src/Providers/ViaCepProvider.php index c3bab0b..065a60d 100644 --- a/src/Providers/ViaCepProvider.php +++ b/src/Providers/ViaCepProvider.php @@ -2,11 +2,11 @@ namespace Claudsonm\CepPromise\Providers; -use Claudsonm\CepPromise\Contracts\BaseProvider; -use Claudsonm\CepPromise\Exceptions\CepPromiseProviderException; use Exception; -use GuzzleHttp\Exception\RequestException; use Psr\Http\Message\ResponseInterface; +use GuzzleHttp\Exception\RequestException; +use Claudsonm\CepPromise\Contracts\BaseProvider; +use Claudsonm\CepPromise\Exceptions\CepPromiseProviderException; class ViaCepProvider extends BaseProvider { diff --git a/tests/Feature/CepPromiseFeatureTest.php b/tests/Feature/CepPromiseFeatureTest.php index a492be9..df1eb70 100644 --- a/tests/Feature/CepPromiseFeatureTest.php +++ b/tests/Feature/CepPromiseFeatureTest.php @@ -27,41 +27,19 @@ public function testExceptionFetchingNonExistentCep() public function testFetchingUsingValidIntegerWithoutLeadingZeros() { - $addressRetrieved = CepPromise::fetch(5010000); - $this->assertInstanceOf(Address::class, $addressRetrieved); - - return $addressRetrieved; - } - - public function testFetchingUsingValidStringWithLeadingZeros() - { - $addressRetrieved = CepPromise::fetch('05010000'); - $this->assertInstanceOf(Address::class, $addressRetrieved); - - return $addressRetrieved; - } - - /** - * @depends testFetchingUsingValidIntegerWithoutLeadingZeros - * - * @param \Claudsonm\CepPromise\Address $address - */ - public function testInformationRetrievedFromIntegerWithoutLeadingZeros(Address $address) - { - $this->assertEquals('São Paulo', $address->city); - $this->assertEquals('Perdizes', $address->district); + $address = CepPromise::fetch(8542130); + $this->assertInstanceOf(Address::class, $address); + $this->assertEquals('Ferraz de Vasconcelos', $address->city); + $this->assertEquals('Cidade Kemel', $address->district); $this->assertEquals('SP', $address->state); - $this->assertEquals('Rua Caiubi', $address->street); - $this->assertEquals('05010000', $address->zipCode); + $this->assertEquals('Avenida Luiz Rosa da Costa', $address->street); + $this->assertEquals('08542130', $address->zipCode); } - /** - * @depends testFetchingUsingValidStringWithLeadingZeros - * - * @param \Claudsonm\CepPromise\Address $address - */ - public function testInformationRetrievedFromStringWithLeadingZeros(Address $address) + public function testFetchingUsingValidStringWithLeadingZeros() { + $address = CepPromise::fetch('05010000'); + $this->assertInstanceOf(Address::class, $address); $this->assertEquals('São Paulo', $address->city); $this->assertEquals('Perdizes', $address->district); $this->assertEquals('SP', $address->state); diff --git a/tests/Unit/CepPromiseUnitTest.php b/tests/Unit/CepPromiseUnitTest.php index 73890d4..16c1a38 100644 --- a/tests/Unit/CepPromiseUnitTest.php +++ b/tests/Unit/CepPromiseUnitTest.php @@ -2,10 +2,11 @@ namespace Claudsonm\CepPromise\Tests\Unit; +use ReflectionMethod; +use PHPUnit\Framework\TestCase; +use Claudsonm\CepPromise\Address; use Claudsonm\CepPromise\CepPromise; use Claudsonm\CepPromise\Exceptions\CepPromiseException; -use PHPUnit\Framework\TestCase; -use ReflectionMethod; class CepPromiseUnitTest extends TestCase { @@ -51,4 +52,49 @@ public function testIfFetchMethodIsStatic() $fetchMethod = new ReflectionMethod(CepPromise::class, 'fetch'); $this->assertTrue($fetchMethod->isStatic()); } + + public function testAnAddressCanBeConvertedToAnArray() + { + $address = $this->getTestAddressAsObject(); + $this->assertEqualsCanonicalizing($this->getTestAddressAsArray(), $address->toArray()); + } + + public function testAnAddressCanBeCreatedFromAnArray() + { + $address = Address::create($this->getTestAddressAsArray()); + $this->assertEqualsCanonicalizing($this->getTestAddressAsObject(), $address); + } + + /** + * Retorna o endereço de teste na forma de um array associativo. + * + * @return array + */ + private function getTestAddressAsArray(): array + { + return [ + 'city' => 'Aracaju', + 'district' => 'Santo Antônio', + 'state' => 'SE', + 'street' => 'Avenida Presidente Juscelino Kubitschek', + 'zipCode' => '49060535', + ]; + } + + /** + * Retorna o endereço de teste na forma de um objeto. + * + * @return Address + */ + private function getTestAddressAsObject(): Address + { + $address = new Address(); + $address->city = 'Aracaju'; + $address->state = 'SE'; + $address->street = 'Avenida Presidente Juscelino Kubitschek'; + $address->district = 'Santo Antônio'; + $address->zipCode = '49060535'; + + return $address; + } } From a2d40b39530597d8b54a98024a9ed5788f931546 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Sat, 14 Sep 2019 01:35:59 -0300 Subject: [PATCH 3/3] =?UTF-8?q?Atualizada=20descri=C3=A7=C3=A3o=20do=20rea?= =?UTF-8?q?dme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f9e8777..ae4fac8 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![StyleCI](https://github.styleci.io/repos/177436507/shield?branch=master)](https://github.styleci.io/repos/177436507) [![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors) -Um pacote para busca de CEPs em diversos serviços utilizando [Promises/A+](https://promisesaplus.com/). +Um pacote agnóstico para PHP 7.0+ que efetua a busca de CEPs em diversos serviços utilizando [Promises/A+](https://promisesaplus.com/). Inspirado no pacote [CEP Promise](https://github.com/filipedeschamps/cep-promise) para Node.js e web browsers. @@ -11,7 +11,7 @@ para Node.js e web browsers. - Realiza requests de forma concorrente, retornando sempre a resposta mais rápida; - Possui alta disponibilidade por utilizar diversos provedores de serviço diferentes; - Base de CEPs sempre atualizada, já que conecta-se com diversos serviços, dentre eles os Correios; -- Sem limites de requisições (rate limits) conhecidas; +- Sem limites de requisições (*rate limits*) conhecidas; - Feito utilizando a implementação para PHP de promises do pacote [guzzle/promises](https://github.com/guzzle/promises); ## Instalação @@ -163,4 +163,4 @@ Um muito obrigado a todos os serumaninhos que contribuiram com este repositório -Este projeto segue a especificação do [all-contributors](https://github.com/all-contributors/all-contributors). Contribuições de qualquer natureza são bem vindas! \ No newline at end of file +Este projeto segue a especificação do [all-contributors](https://github.com/all-contributors/all-contributors). Contribuições de qualquer natureza são bem vindas!