-
Notifications
You must be signed in to change notification settings - Fork 0
[v2][cpf-dv] Create cpf-dv package for CPF check digit calculation
#36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
de3488c
docs(utils): include "PHP v8.5" in the PHP supported versions
juliolmuller c69a1a1
chore: disable PhpStan rule
juliolmuller 83e93c6
chore(cpf-dv): create new package in monorepo
juliolmuller 5f0463c
feat(cpf-dv): create errors and exceptions for package
juliolmuller 0735243
feat(cpf-dv): define constants for package
juliolmuller 25b5de3
feat(cpf-dv): implement main class of the package
juliolmuller 870723c
docs(cpf-dv): create README documentation
juliolmuller 91cea40
docs(cpf-dv): create Portuguese version of documentation
juliolmuller fc7a521
docs(cpf-dv): create CHANGELOG file
juliolmuller f8b4777
test(cpf-dv): create unit tests for all resources
juliolmuller 8c96008
ci: include package `cpf-dv` in CI workflow
juliolmuller 03116c6
fix(cpf-dv): fix error message
juliolmuller 1a6dd10
style(cpf-dv): fix indentation
juliolmuller dad6b01
style(cpf-dv): fix indentation
juliolmuller eecc8f5
style(cpf-dv): drop unnecessary constructor
juliolmuller fec5272
test(cpf-dv): use appropriate constant to mount path
juliolmuller File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # lacus/cpf-dv | ||
|
|
||
| ## 1.0.0 | ||
|
|
||
| ### 🚀 Stable Version Released! | ||
|
|
||
| Utility class to calculate check digits on CPF (Brazilian Individual's Taxpayer ID). Main features: | ||
|
|
||
| - **Flexible input**: Accepts string or array of strings (formatted or raw). | ||
| - **Format agnostic**: Automatically strips non-numeric characters from input. | ||
| - **Lazy evaluation & caching**: Check digits are calculated only when accessed for the first time. | ||
| - **Minimal dependencies**: [`lacus/utils`](https://packagist.org/packages/lacus/utils) only. | ||
| - **Error handling**: Specific types for type, length, and invalid input scenarios (`TypeError` / `Exception` hierarchy). | ||
|
|
||
| For detailed usage and API reference, see the [README](./README.md). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| MIT License | ||
|
|
||
| Copyright (c) 2026 Julio L. Muller | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
|  | ||
|
|
||
| [](https://packagist.org/packages/lacus/cpf-dv) | ||
| [](https://packagist.org/packages/lacus/cpf-dv) | ||
| [](https://www.php.net/) | ||
| [](https://github.com/LacusSolutions/br-utils-php/actions) | ||
| [](https://github.com/LacusSolutions/br-utils-php) | ||
| [](https://github.com/LacusSolutions/br-utils-php/blob/main/LICENSE) | ||
|
|
||
| > 🌎 [Acessar documentação em português](https://github.com/LacusSolutions/br-utils-php/blob/main/packages/cpf-dv/README.pt.md) | ||
|
|
||
| A PHP utility to calculate check digits on CPF (Brazilian Individual's Taxpayer ID). | ||
|
|
||
| ## PHP Support | ||
|
|
||
| |  |  |  |  | | ||
| | --- | --- | --- | --- | | ||
| | Passing ✔ | Passing ✔ | Passing ✔ | Passing ✔ | | ||
|
|
||
| ## Features | ||
|
|
||
| - ✅ **Flexible input**: Accepts `string` or `array` of strings | ||
| - ✅ **Format agnostic**: Automatically strips non-numeric characters from string input | ||
| - ✅ **Auto-expansion**: Multi-character strings in arrays are expanded to individual digits | ||
| - ✅ **Lazy evaluation**: Check digits are calculated only when accessed (via properties) | ||
| - ✅ **Caching**: Calculated values are cached for subsequent access | ||
| - ✅ **Property-style API**: `first`, `second`, `both`, `cpf` (via magic `__get`) | ||
| - ✅ **Minimal dependencies**: Only [`lacus/utils`](https://packagist.org/packages/lacus/utils) | ||
| - ✅ **Error handling**: Specific types for type, length, and invalid CPF scenarios (`TypeError` vs `Exception` semantics) | ||
|
|
||
| ## Installation | ||
|
|
||
| ```bash | ||
| # using Composer | ||
| $ composer require lacus/cpf-dv | ||
| ``` | ||
|
|
||
| ## Quick Start | ||
|
|
||
| ```php | ||
| <?php | ||
|
|
||
| use Lacus\BrUtils\Cpf\CpfCheckDigits; | ||
|
|
||
| $checkDigits = new CpfCheckDigits('054496519'); | ||
|
|
||
| $checkDigits->first; // '1' | ||
| $checkDigits->second; // '0' | ||
| $checkDigits->both; // '10' | ||
| $checkDigits->cpf; // '05449651910' | ||
| ``` | ||
|
|
||
| ## Usage | ||
|
|
||
| The main resource of this package is the class `CpfCheckDigits`. Through an instance, you access CPF check-digit information: | ||
|
|
||
| - **`__construct`**: `new CpfCheckDigits(string|array $cpfInput)` — 9–11 digits (formatting stripped from strings). | ||
| - **`first`**: First check digit (10th digit of the CPF). Lazy, cached. | ||
| - **`second`**: Second check digit (11th digit of the CPF). Lazy, cached. | ||
| - **`both`**: Both check digits concatenated as a string. | ||
| - **`cpf`**: The complete CPF as a string of 11 digits (9 base digits + 2 check digits). | ||
|
|
||
| ### Input formats | ||
|
|
||
| The `CpfCheckDigits` class accepts multiple input formats: | ||
|
|
||
| **String input:** plain digits or formatted CPF (e.g. `054.496.519-10`). Non-numeric characters are automatically stripped. Use 9 digits (base only) or 11 digits (only the first 9 are used). | ||
|
|
||
| **Array of strings:** single-character strings or multi-character strings (expanded to individual digits), e.g. `['0','5','4','4','9','6','5','1','9']`, `['054496519']`, `['054','496','519']`. | ||
|
|
||
| ### Errors & exceptions handling | ||
|
|
||
| This package uses **TypeError vs Exception** semantics: *type errors* indicate incorrect API use (e.g. wrong type); *exceptions* indicate invalid or ineligible data (e.g. invalid CPF). You can catch specific classes or use the abstract bases. | ||
|
|
||
| - **CpfCheckDigitsTypeError** (_abstract_) — base for type errors; extends PHP’s `TypeError` | ||
| - **CpfCheckDigitsInputTypeError** — input is not `string` or `string[]` | ||
| - **CpfCheckDigitsException** (_abstract_) — base for data/flow exceptions; extends `Exception` | ||
| - **CpfCheckDigitsInputLengthException** — sanitized length is not 9–11 | ||
| - **CpfCheckDigitsInputInvalidException** — input ineligible (e.g. repeated digits like `111111111`) | ||
|
|
||
| ```php | ||
| <?php | ||
|
|
||
| use Lacus\BrUtils\Cpf\CpfCheckDigits; | ||
| use Lacus\BrUtils\Cpf\Exceptions\CpfCheckDigitsException; | ||
| use Lacus\BrUtils\Cpf\Exceptions\CpfCheckDigitsInputInvalidException; | ||
| use Lacus\BrUtils\Cpf\Exceptions\CpfCheckDigitsInputLengthException; | ||
| use Lacus\BrUtils\Cpf\Exceptions\CpfCheckDigitsInputTypeError; | ||
|
|
||
| // Input type (e.g. integer not allowed) | ||
| try { | ||
| new CpfCheckDigits(12345678901); | ||
| } catch (CpfCheckDigitsInputTypeError $e) { | ||
| echo $e->getMessage(); | ||
| } | ||
|
|
||
| // Length (must be 9–11 digits after sanitization) | ||
| try { | ||
| new CpfCheckDigits('12345678'); | ||
| } catch (CpfCheckDigitsInputLengthException $e) { | ||
| echo $e->getMessage(); | ||
| } | ||
|
|
||
| // Invalid (e.g. repeated digits) | ||
| try { | ||
| new CpfCheckDigits(['999', '999', '999']); | ||
| } catch (CpfCheckDigitsInputInvalidException $e) { | ||
| echo $e->getMessage(); | ||
| } | ||
|
|
||
| // Any data exception from the package | ||
| try { | ||
| // risky code | ||
| } catch (CpfCheckDigitsException $e) { | ||
| // handle | ||
| } | ||
| ``` | ||
|
|
||
| ### Other available resources | ||
|
|
||
| - **`CPF_MIN_LENGTH`**: `9` — class constant `CpfCheckDigits::CPF_MIN_LENGTH`, and global `Lacus\BrUtils\Cpf\CPF_MIN_LENGTH` when the autoloaded `cpf-dv.php` file is loaded. | ||
| - **`CPF_MAX_LENGTH`**: `11` — class constant `CpfCheckDigits::CPF_MAX_LENGTH`, and global `Lacus\BrUtils\Cpf\CPF_MAX_LENGTH` when `cpf-dv.php` is loaded. | ||
|
|
||
| ## Calculation algorithm | ||
|
|
||
| The package calculates CPF check digits using the official Brazilian algorithm: | ||
|
|
||
| 1. **First check digit (10th position):** digits 1–9 of the CPF base; weights 10, 9, 8, 7, 6, 5, 4, 3, 2 (from left to right); `remainder = 11 - (sum(digit × weight) % 11)`; result is `0` if remainder > 9, otherwise `remainder`. | ||
| 2. **Second check digit (11th position):** digits 1–9 + first check digit; weights 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 (from left to right); same formula. | ||
|
|
||
| ## Contribution & Support | ||
|
|
||
| We welcome contributions! Please see our [Contributing Guidelines](https://github.com/LacusSolutions/br-utils-php/blob/main/CONTRIBUTING.md) for details. If you find this project helpful, please consider: | ||
|
|
||
| - ⭐ Starring the repository | ||
| - 🤝 Contributing to the codebase | ||
| - 💡 [Suggesting new features](https://github.com/LacusSolutions/br-utils-php/issues) | ||
| - 🐛 [Reporting bugs](https://github.com/LacusSolutions/br-utils-php/issues) | ||
|
|
||
| ## License | ||
|
|
||
| This project is licensed under the MIT License — see the [LICENSE](https://github.com/LacusSolutions/br-utils-php/blob/main/LICENSE) file for details. | ||
|
|
||
| ## Changelog | ||
|
|
||
| See [CHANGELOG](https://github.com/LacusSolutions/br-utils-php/blob/main/packages/cpf-dv/CHANGELOG.md) for a list of changes and version history. | ||
|
|
||
| --- | ||
|
|
||
| Made with ❤️ by [Lacus Solutions](https://github.com/LacusSolutions) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
|  | ||
|
|
||
| > 🌎 [Access documentation in English](https://github.com/LacusSolutions/br-utils-php/blob/main/packages/cpf-dv/README.md) | ||
|
|
||
| Utilitário em PHP para calcular os dígitos verificadores de CPF (Cadastro de Pessoa Física). | ||
|
|
||
| ## Recursos | ||
|
|
||
| - ✅ **Entrada flexível**: Aceita `string` ou `array` de strings | ||
| - ✅ **Agnóstico ao formato**: Remove automaticamente caracteres não numéricos da entrada em string | ||
| - ✅ **Auto-expansão**: Strings com vários caracteres em arrays são expandidas para dígitos individuais | ||
| - ✅ **Avaliação lazy**: Dígitos verificadores são calculados apenas quando acessados (via propriedades) | ||
| - ✅ **Cache**: Valores calculados são armazenados em cache para acessos subsequentes | ||
| - ✅ **API estilo propriedades**: `first`, `second`, `both`, `cpf` (via `__get` mágico) | ||
| - ✅ **Dependências mínimas**: Apenas [`lacus/utils`](https://packagist.org/packages/lacus/utils) | ||
| - ✅ **Tratamento de erros**: Tipos específicos para tipo, tamanho e CPF inválido (semântica `TypeError` vs `Exception`) | ||
|
|
||
| ## Instalação | ||
|
|
||
| ```bash | ||
| # usando Composer | ||
| $ composer require lacus/cpf-dv | ||
| ``` | ||
|
|
||
| ## Início rápido | ||
|
|
||
| ```php | ||
| <?php | ||
|
|
||
| use Lacus\BrUtils\Cpf\CpfCheckDigits; | ||
|
|
||
| $checkDigits = new CpfCheckDigits('054496519'); | ||
|
|
||
| $checkDigits->first; // '1' | ||
| $checkDigits->second; // '0' | ||
| $checkDigits->both; // '10' | ||
| $checkDigits->cpf; // '05449651910' | ||
| ``` | ||
|
|
||
| ## Utilização | ||
|
|
||
| O principal recurso deste pacote é a classe `CpfCheckDigits`. Por meio da instância, você acessa as informações dos dígitos verificadores do CPF: | ||
|
|
||
| - **`__construct`**: `new CpfCheckDigits(string|array $cpfInput)` — 9–11 dígitos (formatação removida de strings). | ||
| - **`first`**: Primeiro dígito verificador (10º dígito do CPF). Lazy, em cache. | ||
| - **`second`**: Segundo dígito verificador (11º dígito do CPF). Lazy, em cache. | ||
| - **`both`**: Ambos os dígitos verificadores concatenados em uma string. | ||
| - **`cpf`**: O CPF completo como string de 11 dígitos (9 da base + 2 dígitos verificadores). | ||
|
|
||
| ### Formatos de entrada | ||
|
|
||
| A classe `CpfCheckDigits` aceita múltiplos formatos de entrada: | ||
|
|
||
| **String:** dígitos crus ou CPF formatado (ex.: `054.496.519-10`). Caracteres não numéricos são removidos automaticamente. Use 9 dígitos (apenas base) ou 11 dígitos (apenas os 9 primeiros são usados). | ||
|
|
||
| **Array de strings:** strings de um caractere ou de vários (expandidas para dígitos individuais), ex.: `['0','5','4','4','9','6','5','1','9']`, `['054496519']`, `['054','496','519']`. | ||
|
|
||
| ### Erros e exceções | ||
|
|
||
| Este pacote usa a distinção **TypeError vs Exception**: *erros de tipo* indicam uso incorreto da API (ex.: tipo errado); *exceções* indicam dados inválidos ou ineligíveis (ex.: CPF inválido). Você pode capturar classes específicas ou as bases abstratas. | ||
|
|
||
| - **CpfCheckDigitsTypeError** (_abstract_) — base para erros de tipo; estende o `TypeError` do PHP | ||
| - **CpfCheckDigitsInputTypeError** — entrada não é `string` nem `string[]` | ||
| - **CpfCheckDigitsException** (_abstract_) — base para exceções de dados/fluxo; estende `Exception` | ||
| - **CpfCheckDigitsInputLengthException** — tamanho após sanitização não é 9–11 | ||
| - **CpfCheckDigitsInputInvalidException** — entrada ineligível (ex.: dígitos repetidos como `111111111`) | ||
|
|
||
| ```php | ||
| <?php | ||
|
|
||
| use Lacus\BrUtils\Cpf\CpfCheckDigits; | ||
| use Lacus\BrUtils\Cpf\Exceptions\CpfCheckDigitsException; | ||
| use Lacus\BrUtils\Cpf\Exceptions\CpfCheckDigitsInputInvalidException; | ||
| use Lacus\BrUtils\Cpf\Exceptions\CpfCheckDigitsInputLengthException; | ||
| use Lacus\BrUtils\Cpf\Exceptions\CpfCheckDigitsInputTypeError; | ||
|
|
||
| // Tipo de entrada (ex.: inteiro não permitido) | ||
| try { | ||
| new CpfCheckDigits(12345678901); | ||
| } catch (CpfCheckDigitsInputTypeError $e) { | ||
| echo $e->getMessage(); | ||
| } | ||
|
|
||
| // Tamanho (deve ser 9–11 dígitos após sanitização) | ||
| try { | ||
| new CpfCheckDigits('12345678'); | ||
| } catch (CpfCheckDigitsInputLengthException $e) { | ||
| echo $e->getMessage(); | ||
| } | ||
|
|
||
| // Inválido (ex.: dígitos repetidos) | ||
| try { | ||
| new CpfCheckDigits(['999', '999', '999']); | ||
| } catch (CpfCheckDigitsInputInvalidException $e) { | ||
| echo $e->getMessage(); | ||
| } | ||
|
|
||
| // Qualquer exceção de dados do pacote | ||
| try { | ||
| // código arriscado | ||
| } catch (CpfCheckDigitsException $e) { | ||
| // tratar | ||
| } | ||
| ``` | ||
|
|
||
| ### Outros recursos disponíveis | ||
|
|
||
| - **`CPF_MIN_LENGTH`**: `9` — constante de classe `CpfCheckDigits::CPF_MIN_LENGTH`, e constante global `Lacus\BrUtils\Cpf\CPF_MIN_LENGTH` quando `cpf-dv.php` é carregado pelo autoload do Composer. | ||
| - **`CPF_MAX_LENGTH`**: `11` — constante de classe `CpfCheckDigits::CPF_MAX_LENGTH`, e constante global `Lacus\BrUtils\Cpf\CPF_MAX_LENGTH` quando `cpf-dv.php` é carregado pelo autoload do Composer. | ||
|
|
||
| ## Algoritmo de cálculo | ||
|
|
||
| O pacote calcula os dígitos verificadores do CPF usando o algoritmo oficial brasileiro: | ||
|
|
||
| 1. **Primeiro dígito (10ª posição):** dígitos 1–9 da base do CPF; pesos 10, 9, 8, 7, 6, 5, 4, 3, 2 (da esquerda para a direita); `resto = 11 - (soma(dígito × peso) % 11)`; resultado é `0` se resto > 9, caso contrário `resto`. | ||
| 2. **Segundo dígito (11ª posição):** dígitos 1–9 + primeiro dígito verificador; pesos 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 (da esquerda para a direita); mesma fórmula. | ||
|
|
||
| ## Contribuição e suporte | ||
|
|
||
| Contribuições são bem-vindas! Consulte as [Diretrizes de contribuição](https://github.com/LacusSolutions/br-utils-php/blob/main/CONTRIBUTING.md). Se o projeto for útil para você, considere: | ||
|
|
||
| - ⭐ Dar uma estrela no repositório | ||
| - 🤝 Contribuir com código | ||
| - 💡 [Sugerir novas funcionalidades](https://github.com/LacusSolutions/br-utils-php/issues) | ||
| - 🐛 [Reportar bugs](https://github.com/LacusSolutions/br-utils-php/issues) | ||
|
|
||
| ## Licença | ||
|
|
||
| Este projeto está sob a licença MIT — veja o arquivo [LICENSE](https://github.com/LacusSolutions/br-utils-php/blob/main/LICENSE). | ||
|
|
||
| ## Changelog | ||
|
|
||
| Veja o [CHANGELOG](https://github.com/LacusSolutions/br-utils-php/blob/main/packages/cpf-dv/CHANGELOG.md) para alterações e histórico de versões. | ||
|
|
||
| --- | ||
|
|
||
| Feito com ❤️ por [Lacus Solutions](https://github.com/LacusSolutions) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.