zanchi/viacep 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

zanchi/viacep

Composer 安装命令:

composer require zanchi/viacep

包简介

CEP search Brazilian utilizes

关键字:

README 文档

README

Simple utilities to consume the public ViaCEP API (https://viacep.com.br/).

This package exposes two main services to query addresses and two DTOs to represent the returned data.

  • Services:
    • Zanchi\ViaCep\Service\ViaCepGetByCepService
    • Zanchi\ViaCep\Service\ViaCepGetBySearchService
  • DTOs:
    • Zanchi\ViaCep\Dtos\CepDto
    • Zanchi\ViaCep\Dtos\ViaCepDto and Zanchi\ViaCep\Dtos\ViaCepArray (collection)

Requirements

  • PHP ^7.4
  • Extensions: ext-json, ext-curl

When installed via Composer, PSR-4 autoload is already configured (root namespace: Zanchi\\ViaCep\\).

How it works (overview)

  • ViaCepGetByCepService: queries a single CEP (e.g., 01001-000) and returns a ViaCepDto or null if not found.
  • ViaCepGetBySearchService: searches by UF (state) + city + street and returns a ViaCepArray collection with 0..N results (each one is a ViaCepDto).
  • CepDto: encapsulates a CEP with formatting helpers (with/without hyphen). The value is sanitized to keep only digits.

Relevant exceptions:

  • Zanchi\ViaCep\Exceptions\ViaCepRequestInvalidException: problems during the HTTP request or JSON parsing.
  • \InvalidArgumentException: input validations (e.g., invalid UF, too-short strings, wrong parameter type).

Service: ViaCepGetByCepService

Namespace: Zanchi\\ViaCep\\Service\\ViaCepGetByCepService

Main signature:

  • public function execute(CepDto|string $cepDto): ?ViaCepDto

Rules/validation:

  • Accepts a CepDto or a string with the CEP.
  • If a string is provided, a CepDto instance is created internally (the string is sanitized to contain digits only).
  • On HTTP/JSON error, ViaCepRequestInvalidException will be thrown.

Return value:

  • ViaCepDto when the CEP is found.
  • null when the API returns an empty result (not found).

Usage example:

use Zanchi\ViaCep\Service\ViaCepGetByCepService;
use Zanchi\ViaCep\Dtos\CepDto;

$service = new ViaCepGetByCepService();

// Option 1: passing a string
$dto = $service->execute('01001-000');

// Option 2: passing a CepDto
//$dto = $service->execute(new CepDto('01001000'));

if ($dto !== null) {
    echo $dto->logradouro . PHP_EOL;           // Praça da Sé
    echo $dto->bairro . PHP_EOL;               // Sé
    echo $dto->localidade . ' - ' . $dto->uf;  // São Paulo - SP
}

Service: ViaCepGetBySearchService

Namespace: Zanchi\\ViaCep\\Service\\ViaCepGetBySearchService

Main signature:

  • public function execute(string $uf, string $cidade, string $logradouro): ViaCepArray

Rules/validation:

  • uf must have exactly 2 characters; it is converted to uppercase.
  • cidade (city) must have at least 3 characters; spaces are encoded as %20.
  • logradouro (street) must have at least 3 characters; spaces are replaced with +.
  • On HTTP/JSON error, ViaCepRequestInvalidException will be thrown.

Return value:

  • ViaCepArray, a collection (Countable, ArrayAccess, JsonSerializable) containing ViaCepDto.

Usage example:

use Zanchi\ViaCep\Service\ViaCepGetBySearchService;

$service = new ViaCepGetBySearchService();
$results = $service->execute('SP', 'São Paulo', 'Praça da Sé');

echo 'Total: ' . count($results) . PHP_EOL;

foreach ($results->all() as $item) { // $item is a ViaCepDto
    echo $item->logradouro . ' - ' . $item->bairro . ' - ' . $item->localidade . '/' . $item->uf . PHP_EOL;
}

// You can also access by index:
//$first = $results[0] ?? null;

DTO: CepDto

Namespace: Zanchi\\ViaCep\\Dtos\\CepDto

Responsibility:

  • Encapsulate a CEP and provide formatting helpers.

Important behavior:

  • The constructor sanitizes the input, keeping digits only (removes dots, hyphen, spaces, etc.).
  • Methods:
    • unformatted(): string — returns the 8 digits only (e.g., "01001000").
    • formatted(): string — returns the standard format with hyphen (e.g., "01001-000").

Note:

  • The class contains an internal length validation routine (8 digits), but the explicit check is not invoked externally. When using the services, if the CEP is invalid, the API may simply return no result.

Quick example:

use Zanchi\ViaCep\Dtos\CepDto;

$cep = new CepDto('01001-000');
echo $cep->unformatted(); // 01001000
echo $cep->formatted();   // 01001-000

DTOs: ViaCepDto and ViaCepArray

  • ViaCepDto represents the payload of an address returned by the ViaCEP API. Typical fields: cep (as CepDto), logradouro, bairro, localidade, uf, ibge, etc.
    • Factories: ViaCepDto::fromArray(array $data), ViaCepDto::fromJson(string $json).
    • Serialization: toArray() and jsonSerialize().
  • ViaCepArray is a collection of ViaCepDto.
    • Factory: ViaCepArray::fromArray(array $data) (usually the array returned by the API when searching by street).
    • Methods: count(), all(), index access ($list[0]), and jsonSerialize().

Error handling

  • Network failures, non-2xx HTTP responses or invalid JSON: Zanchi\ViaCep\Exceptions\ViaCepRequestInvalidException.
  • Invalid parameters (e.g., UF with wrong size, wrong types, too-short strings): \InvalidArgumentException.

Suggestion: wrap calls in try/catch to handle expected errors:

use Zanchi\ViaCep\Service\ViaCepGetByCepService;
use Zanchi\ViaCep\Exceptions\ViaCepRequestInvalidException;

$service = new ViaCepGetByCepService();

try {
    $dto = $service->execute('01001-000');
} catch (ViaCepRequestInvalidException $e) {
    // Handle request/JSON errors
} catch (\InvalidArgumentException $e) {
    // Handle input validations
}

Running tests

This repository includes sample tests (folder tests/). Adjust environment and connectivity as needed to run real calls to ViaCEP.

License

MIT

统计信息

  • 总下载量: 1
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-08-14