safeaccess/identum 问题修复 & 功能扩展

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

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

safeaccess/identum

Composer 安装命令:

composer require safeaccess/identum

包简介

Brazilian document validation library (CPF, CNPJ, CEP, CNH, CNS, PIS, IE, RENAVAM, Voter Title, Mercosul Plate)

README 文档

README

safeaccess-identum logo

Safe Access Identum — PHP

PHP library for validating Brazilian documents — CPF, CNPJ, CNH, CEP, CNS, PIS, IE (all 27 states), RENAVAM, Mercosul Plate, Voter Title, Payment Card, PIX key, and Certificate. Input sanitization by default. Zero production dependencies.

Packagist License: MIT PHP 8.2+ PHPStan max Tested with Pest Infection MSI

Version 2.0. validate() now returns a rich result object instead of a boolean, with new capabilities (format, generate, metadata) and document types. Upgrading from 1.x? See Migrating from 1.x.

Features

  • 13 document types — CPF, CNPJ (alphanumeric), CNH, CEP, CNS, PIS, IE (all 27 states), RENAVAM, Mercosul Plate, Voter Title, plus Payment Card (Luhn), PIX key, and civil-registry Certificate
  • Rich resultvalidate() returns { valid, reason, normalized, meta }; isValid() is the boolean shortcut
  • Machine-readable reasons — every failure carries a stable ReasonCode (invalid_format, wrong_length, bad_check_digit, unknown_uf, known_invalid, denied)
  • Metadata extraction — offline, from the number: CPF/IE uf, CNS type, CNPJ isMatriz/isAlphanumeric, Card brand, PIX keyType, Certificate type
  • format() / strip() — apply or remove the canonical mask
  • generate() — valid documents for tests (Identum::generateCpf(), …)
  • IE all 27 states — every state algorithm implemented and tested with edge cases
  • Input sanitization by default'529.982.247-25' and '52998224725' both just work
  • Allow list / deny list — force-accept or force-reject specific values (allow list wins)
  • 100% line + branch coverage — tested with Pest 3 · Infection mutation testing (≥ 85% MSI)
  • Zero production dependencies — pure PHP 8.2+

The problem

Validating Brazilian documents in PHP accumulates silently: scattered regexes, copy-pasted Mod-11 loops, and 27 state-specific IE algorithms scattered across the codebase. Each re-implementation gets Bahia's dual-modulus branch wrong and ships with no edge-case tests.

Without this library:

function validateCpf(string $cpf): bool {
    $cpf = preg_replace('/\D/', '', $cpf);
    if (strlen($cpf) !== 11 || preg_match('/(\d)\1{10}/', $cpf)) return false;
    // 30+ lines: loops, hardcoded weights, manual digit comparison...
}

With this library:

Identum::cpf('529.982.247-25')->isValid();                    // true
Identum::ie('343.173.196.450', StateEnum::SP)->isValid();     // true — all 27 states

Installation

composer require safeaccess/identum

Requirements: PHP 8.2+

Quick start

use SafeAccess\Identum\Identum;
use SafeAccess\Identum\Assets\IE\StateEnum;
use SafeAccess\Identum\Exceptions\ValidationException;

// Boolean shortcut — formatting stripped automatically
Identum::cpf('529.982.247-25')->isValid();                       // true
Identum::cnpj('84.773.274/0001-03')->isValid();                  // true
Identum::cnpj('A0000000000032')->isValid();                      // true — alphanumeric CNPJ
Identum::cnh('22522791508')->isValid();                          // true
Identum::cep('78000-000')->isValid();                            // true
Identum::cns('100000000060018')->isValid();                      // true
Identum::pis('329.9506.158-9')->isValid();                       // true
Identum::ie('343.173.196.450', StateEnum::SP)->isValid();        // true — all 27 states
Identum::renavam('60390908553')->isValid();                      // true
Identum::placa('ABC1D23')->isValid();                            // true — Mercosul format
Identum::tituloEleitor('123456781295')->isValid();               // true
Identum::cartao('4111111111111111')->isValid();                  // true — Luhn
Identum::pix('pix@bcb.gov.br')->isValid();                       // true — PIX key
Identum::certidao('00188301551987100018050000056665')->isValid();// true — certificate

// Rich result — why it failed, the normalized value, and extracted metadata
$result = Identum::cpf('529.982.247-25')->validate();
$result->valid;       // true
$result->reason;      // null (a ReasonCode enum when invalid)
$result->normalized;  // '52998224725'
$result->meta?->uf;   // 'SP' — fiscal region

// Validate or throw — the exception carries structured context
try {
    Identum::cpf('000.000.000-00')->validateOrFail();
} catch (ValidationException $e) {
    $e->document;   // 'cpf'
    $e->reason;     // ReasonCode::KnownInvalid
    $e->normalized; // '00000000000'
}

// Allow list / deny list (format-agnostic)
Identum::cpf('529.982.247-25')->denyList(['52998224725'])->isValid();   // false
Identum::cpf('000.000.000-00')->allowList(['000.000.000-00'])->isValid(); // true

// Format / strip / generate
Identum::cpf('52998224725')->format();      // '529.982.247-25'
Identum::cpf('529.982.247-25')->strip();    // '52998224725'
Identum::generateCpf();                      // e.g. '76502099010'
Identum::generateCnpj(formatted: true);      // e.g. '12.345.678/0001-95'

Direct instantiation

use SafeAccess\Identum\Assets\CPF\CPFValidation;

$validator = new CPFValidation('529.982.247-25');
$validator->isValid(); // true

API

All validator classes share the same fluent interface after construction:

Method Return Description
validate() ValidationResult Rich result: { valid, reason, normalized, meta }
isValid() bool Boolean shortcut for validate()->valid
validateOrFail() void Throws ValidationException (with document, reason, normalized) when invalid
format() string Canonical mask applied, best-effort
strip() string Canonical value with mask characters removed
denyList(string[]) static Force-reject the specified values regardless of checksum
allowList(string[]) static Force-accept the specified values regardless of checksum
raw() string The input exactly as provided

blacklist() / whitelist() still work as deprecated aliases of denyList() / allowList() and will be removed in 3.0.

Reason codes (stable, snake_case), in the order they are checked: invalid_formatwrong_lengthbad_check_digitunknown_ufknown_invaliddenied.

Generators — one per type on the facade: generateCpf(), generateCnpj(), generateCnh(), generateCep(), generateCns(), generatePis(), generateIe($state), generateRenavam(), generatePlaca(), generateTituloEleitor(). Unmasked by default; pass formatted: true where a mask exists.

Supported documents

Document Alias Class
CPF cpf CPFValidation
CNPJ cnpj CNPJValidation
CNH cnh CNHValidation
CEP cep CEPValidation
CNS cns CNSValidation
PIS/PASEP pis PISValidation
IE ie IEValidation
RENAVAM renavam RenavamValidation
Mercosul Plate placa PlateMercosulValidation
Voter Title tituloEleitor VoterTitleValidation
Payment Card cartao CartaoValidation
PIX key pix PixValidation
Certificate certidao CertidaoValidation

IE — all 27 states

use SafeAccess\Identum\Assets\IE\StateEnum;

Identum::ie('153189458', StateEnum::BA)->isValid();    // Bahia — Mod-10/11 dual
Identum::ie('7908930932562', StateEnum::MG)->isValid(); // Minas Gerais
Identum::ie('P199163724045', StateEnum::SP)->isValid(); // São Paulo rural (P prefix)

CNPJ — alfanumérico

Identum::cnpj('A0000000000032')->isValid(); // true — alphanumeric CNPJ

Payment Card, PIX and Certificate

// Payment card — Luhn integrity only; meta.brand is best-effort BIN detection
Identum::cartao('4111111111111111')->validate()->meta?->brand; // 'visa'

// PIX — any of the five DICT key types; meta.keyType tells which
Identum::pix('+5510998765432')->validate()->meta?->keyType;    // 'phone'

// Civil-registry certificate — 32-digit matrícula (Mod-11 ×10)
Identum::certidao('00188301551987100018050000056665')->validate()->meta?->type; // 'birth'

Card validation is Luhn integrity plus best-effort brand — it does not prove a card exists (that needs an online lookup). PIX validates key format (and CPF/CNPJ checksums), not DICT registration. Both are offline by design.

Contributing

See CONTRIBUTING.md for development setup, commit conventions, and pull request guidelines.

License

MIT © Felipe Sauer

safeaccess/identum 适用场景与选型建议

safeaccess/identum 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8 次下载、GitHub Stars 达 3, 最近一次更新时间为 2026 年 04 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「validation」 「document」 「cpf」 「cnpj」 「brazilian」 「safeaccess」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 safeaccess/identum 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 safeaccess/identum 我们能提供哪些服务?
定制开发 / 二次开发

基于 safeaccess/identum 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-14