Skip to content

Commit

Permalink
Merge pull request #1 from ThiagoCrepequer/dev
Browse files Browse the repository at this point in the history
feat: refactored CEP and created more functions
  • Loading branch information
ThiagoCrepequer authored Apr 28, 2024
2 parents 6a17a25 + 65601be commit 20caa8a
Show file tree
Hide file tree
Showing 5 changed files with 187 additions and 90 deletions.
66 changes: 66 additions & 0 deletions src/Address.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Crepequer\PhpBrasilUtils;

use Crepequer\PhpBrasilUtils\Helpers\Temp;
use DateTime;
use Exception;

final class Address
{
public function __construct(
private bool $saveTemp = false,
private DateTime $validity = new DateTime('+30 days')
)
{}
/**
* This method is responsible for getting the address from the CEP using the ViaCEP API
*
* @param string $cep
* @param bool $error - If true, it will throw an exception if the CEP is invalid
* @param bool $saveTemp - If true, it will save the address in a temporary file
*
* @example getAddresses("12345-678");
* @example getAddresses("98765432");
*
* @return array|bool
*
* @author Thiago Crepequer
*/
public function searchByCep(string $cep, bool|null $error = false): array|bool
{
if (!CEP::validateFormatting($cep, $error)) {
return false;
}

if ($this->saveTemp) {
$temp = Temp::get($cep, "ceps", $this->validity);
if ($temp) {
return $temp;
}
}

$filtredCep = CEP::removeMask($cep);
$url = "https://viacep.com.br/ws/{$filtredCep}/json/";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);

$json = json_decode($response, true);

if (empty($json) || (isset($json["erro"]) && $json["erro"] === true)) {
if ($error) {
throw new Exception("No address found for the CEP: {$cep}");
}
return false;
}

if ($this->saveTemp) {
Temp::set($response, $cep, "ceps");
}

return $json;
}
}
91 changes: 56 additions & 35 deletions src/CEP.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace Crepequer\PhpBrasilUtils;

use Crepequer\PhpBrasilUtils\Traits\Temp;
use Exception;
use InvalidArgumentException;

final class CEP {
Expand Down Expand Up @@ -32,53 +30,76 @@ public static function validateFormatting(string $cep, bool $error = false): boo
}

/**
* This method is responsible for getting the address from the CEP using the ViaCEP API
* This method is responsible for add a mask to CEP
*
* @param string $cep
* @param bool $error - If true, it will throw an exception if the CEP is invalid
* @param bool $saveTemp - If true, it will save the address in a temporary file
*
* @example getAddresses("12345-678");
* @example getAddresses("98765432");
* @example addMask("12345678");
*
* @return array|bool
* @return string
*
* @author Thiago Crepequer
*/
public static function getAddresses(string $cep, bool|null $error = false, bool $saveTemp = false): array|bool
public static function addMask(string $cep): string
{
if (!self::validateFormatting($cep, $error)) {
return false;
}

if ($saveTemp) {
$temp = Temp::getTempJson($cep, "ceps");
if ($temp) {
return $temp;
}
}

$filtredCep = preg_replace("/[^0-9]/", "", $cep);
$url = "https://viacep.com.br/ws/{$filtredCep}/json/";
return substr($cep, 0, 5) . "-" . substr($cep, 5, 3);
}

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
/**
* This method is responsible for remove the mask from CEP
*
* @param string $cep
*
* @example removeMask("12345-678");
*
* @return string
*
* @author Thiago Crepequer
*/
public static function removeMask(string $cep): string
{
return preg_replace("/[^0-9]/", "", $cep);
}

$json = json_decode($response, true);
/**
* This method is responsible for remove the mask from CEP, and convert it to int
* (Note: it will remove 0 from the left of the number, if it exists, please use it carefully)
*
* @param string|int $cep
*
* @example removeMask("12345-678");
*
* @return int
*
* @author Thiago Crepequer
*/
public static function toInt(string|int $cep): int
{
return (int) preg_replace("/[^0-9]/", "", $cep);
}

if (empty($json) || (isset($json["erro"]) && $json["erro"] === true)) {
if ($error) {
throw new Exception("No address found for the CEP: {$cep}");
}
return false;
/**
* This method generate a CEP with random numbers (it's not necessarily a real CEP)
*
* @param bool $mask - If true, it will return the CEP with the mask (xxxxx-xxx)
*
* @return string
*
* @example generate();
*
* @author Thiago Crepequer
*/
public static function generate(bool $mask): string
{
$cep = "";
for ($i = 0; $i < 8; $i++) {
$cep .= rand(0, 9);
}

if ($saveTemp) {
Temp::saveTempJson($response, $cep, "ceps");
if ($mask) {
return self::addMask($cep);
}

return $json;
return $cep;
}
}
24 changes: 13 additions & 11 deletions src/Traits/Temp.php → src/Helpers/Temp.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace Crepequer\PhpBrasilUtils\Traits;
namespace Crepequer\PhpBrasilUtils\Helpers;

use DateTime;
use Exception;
Expand All @@ -14,13 +14,13 @@ final class Temp
* @param string $filename - The name of the file that will be saved
* @param string $folder - The folder where the file will be saved
*
* @example saveTempJson("{}", "file", "folder");
* @example set("{}", "file", "folder");
*
* @return bool
*
* @author Thiago Crepequer
*/
public static function saveTempJson(string $data, string $filename, string $folder): bool
public static function set(string $data, string $filename, string $folder): bool
{
$tempPath = sys_get_temp_dir();

Expand All @@ -35,19 +35,19 @@ public static function saveTempJson(string $data, string $filename, string $fold
}

/**
* This method is responsible for getting the jsons from a temporary file
* This method is responsible for getting the jsons from a temporary file, if it is not found or if it is expired, it will return false
*
* @param string $filename - The name of the file that will be saved
* @param string $folder - The folder where the file will be saved
* @param DateTime $validity - The validity of the file, if it is not set, it will be 30 days
* @param DateTime $validity - The validity of the file, if it is not set, it will be never expired
*
* @example getTempJson("file", "folder");
* @example get("file", "folder");
*
* @return mixed
* @return array|bool
*
* @author Thiago Crepequer
*/
public static function getTempJson(string $filename, string $folder, DateTime $validity = new DateTime('+30 days')): array|bool
public static function get(string $filename, string $folder, DateTime $validity = null): array|bool
{
$tempPath = sys_get_temp_dir();
$filePath = $tempPath . "/$folder" . "/$filename.json";
Expand All @@ -56,9 +56,11 @@ public static function getTempJson(string $filename, string $folder, DateTime $v
return false;
}

$currentTime = new DateTime();
if ($currentTime > $validity) {
return false;
if ($validity) {
$currentTime = new DateTime();
if ($currentTime > $validity) {
return false;
}
}

$data = file_get_contents($filePath);
Expand Down
52 changes: 52 additions & 0 deletions tests/AddressTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace Crepequer\PhpBrasilUtils\Tests;

use Crepequer\PhpBrasilUtils\Address;
use PHPUnit\Framework\TestCase;

final class AddressTest extends TestCase
{

public function testGetAddresses(): void
{
$this->setName("Get address with valid CEP");

$addresses = [
'01001-000',
'70070-600',
'20010000',
'60175045',
'04094050'
];

foreach ($addresses as $cep) {
$returnedAdres = (new Address(saveTemp: true))->searchByCep($cep);
$this->assertIsArray($returnedAdres);
$this->assertArrayHasKey("cep", $returnedAdres);
$this->assertArrayHasKey("logradouro", $returnedAdres);
$this->assertArrayHasKey("complemento", $returnedAdres);
$this->assertArrayHasKey("bairro", $returnedAdres);
$this->assertArrayHasKey("localidade", $returnedAdres);
$this->assertArrayHasKey("uf", $returnedAdres);
$this->assertArrayHasKey("ibge", $returnedAdres);
}
}

public function testGetAdressWithInvalidCEP(): void
{
$this->setName("Get address with invalid CEP but formatted correctly");
$res = (new Address())->searchByCep("12345678");
$this->assertFalse($res);

$this->setName("Get address with invalid CEP and not formatted correctly");
$res = (new Address())->searchByCep("123456789");
$this->assertFalse($res);
}

public function testGetAdressWithInvalidCEPAndErrorTrue(): void
{
$this->expectException(\InvalidArgumentException::class);
(new Address())->searchByCep("123456789", true);
}
}
44 changes: 0 additions & 44 deletions tests/CEPTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,48 +44,4 @@ public function testInvalidCEPFormattingWithoutError(): void
$this->assertFalse($res, "Invalid CEP format");
}
}

public function testGetAddresses(): void
{
$this->setName("Get address with valid CEP");

$addresses = [
'01001-000',
'70070-600',
'20010000',
'60175045',
'04094050'
];

foreach ($addresses as $cep) {
$returnedAdres = CEP::getAddresses($cep);
$this->assertIsArray($returnedAdres);
$this->assertArrayHasKey("cep", $returnedAdres);
$this->assertArrayHasKey("logradouro", $returnedAdres);
$this->assertArrayHasKey("complemento", $returnedAdres);
$this->assertArrayHasKey("bairro", $returnedAdres);
$this->assertArrayHasKey("localidade", $returnedAdres);
$this->assertArrayHasKey("uf", $returnedAdres);
$this->assertArrayHasKey("ibge", $returnedAdres);
}
}

public function testGetAdressWithInvalidCEP(): void
{
$this->setName("Get address with invalid CEP but formatted correctly");
$res = CEP::getAddresses("12345678");
$this->assertFalse($res);

$this->setName("Get address with invalid CEP and not formatted correctly");
$res = CEP::getAddresses("123456789");
$this->assertFalse($res);
}

public function testGetAdressWithInvalidCEPAndErrorTrue(): void
{
$this->setName("Get address with invalid CEP and error true");

$this->expectException(\InvalidArgumentException::class);
CEP::getAddresses("123456789", true);
}
}

0 comments on commit 20caa8a

Please sign in to comment.