Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ jobs:
max-parallel: 2
matrix:
php-version:
- 8.1
- 8.2
- 8.3
- 8.4
Expand Down Expand Up @@ -47,7 +46,6 @@ jobs:
max-parallel: 1
matrix:
php-version:
- 8.1
- 8.2
- 8.3
- 8.4
Expand All @@ -58,6 +56,7 @@ jobs:
- cnpj-gen
- cnpj-val
- cnpj-utils
- cpf-dv
- cpf-fmt
- cpf-gen
- cpf-val
Expand Down
15 changes: 15 additions & 0 deletions packages/cpf-dv/CHANGELOG.md
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).
9 changes: 9 additions & 0 deletions packages/cpf-dv/LICENSE
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.
150 changes: 150 additions & 0 deletions packages/cpf-dv/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
![cpf-dv for PHP](https://br-utils.vercel.app/img/cover_cpf-dv.jpg)

[![Packagist Version](https://img.shields.io/packagist/v/lacus/cpf-dv)](https://packagist.org/packages/lacus/cpf-dv)
[![Packagist Downloads](https://img.shields.io/packagist/dm/lacus/cpf-dv)](https://packagist.org/packages/lacus/cpf-dv)
[![PHP Version](https://img.shields.io/packagist/php-v/lacus/cpf-dv)](https://www.php.net/)
[![Test Status](https://img.shields.io/github/actions/workflow/status/LacusSolutions/br-utils-php/ci.yml?label=ci/cd)](https://github.com/LacusSolutions/br-utils-php/actions)
[![Last Update Date](https://img.shields.io/github/last-commit/LacusSolutions/br-utils-php)](https://github.com/LacusSolutions/br-utils-php)
[![Project License](https://img.shields.io/github/license/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

| ![PHP 8.2](https://img.shields.io/badge/PHP-8.2-777BB4?logo=php&logoColor=white) | ![PHP 8.3](https://img.shields.io/badge/PHP-8.3-777BB4?logo=php&logoColor=white) | ![PHP 8.4](https://img.shields.io/badge/PHP-8.4-777BB4?logo=php&logoColor=white) | ![PHP 8.5](https://img.shields.io/badge/PHP-8.5-777BB4?logo=php&logoColor=white) |
| --- | --- | --- | --- |
| 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)
137 changes: 137 additions & 0 deletions packages/cpf-dv/README.pt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
![cpf-dv para PHP](https://br-utils.vercel.app/img/cover_cpf-dv.jpg)

> 🌎 [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).
Comment thread
juliolmuller marked this conversation as resolved.

## 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)
Loading
Loading