Skip to content

[v2][cnpj-val] Upgrade to latest API and add support to alphanumeric CNPJ format#43

Merged
juliolmuller merged 24 commits into
mainfrom
feat/cnpj-val-v2
May 23, 2026
Merged

[v2][cnpj-val] Upgrade to latest API and add support to alphanumeric CNPJ format#43
juliolmuller merged 24 commits into
mainfrom
feat/cnpj-val-v2

Conversation

@juliolmuller
Copy link
Copy Markdown
Collaborator

@juliolmuller juliolmuller commented May 23, 2026

Summary by CodeRabbit

  • New Features

    • Alphanumeric CNPJ support, batch (array) input, per-call and instance default validation options (type, case sensitivity), and a helper that accepts richer inputs
    • Typed exception hierarchy for input/options validation errors
  • Breaking Changes

    • Public namespaces and API signatures updated; PHP minimum raised to 8.2
    • Default verifier-digit provider changed
  • Documentation

    • Expanded English and Portuguese READMEs and detailed changelog
  • Tests

    • Test suite migrated to Pest/spec style; legacy PHPUnit harness removed
  • Chores

    • Package metadata, test tooling/config, and static-analysis config updated

Review Change Stack

@juliolmuller juliolmuller self-assigned this May 23, 2026
@juliolmuller juliolmuller requested a review from a team as a code owner May 23, 2026 07:41
@juliolmuller juliolmuller added the enhancement New minor or major features. label May 23, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 23, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9276d2ce-cba5-4071-824d-0e8c4934e222

📥 Commits

Reviewing files that changed from the base of the PR and between 0bfca6d and c60c047.

📒 Files selected for processing (1)
  • packages/cnpj-val/README.md

📝 Walkthrough

Walkthrough

The PR refactors the cnpj-val package to version 2.0.0, migrating the namespace to Lacus\BrUtils\Cnpj, introducing an options-driven validator with type enumeration and comprehensive exception hierarchy, and migrating tests from PHPUnit to Pest while expanding documentation for alphanumeric CNPJ support and per-call option overrides.

Changes

CNPJ Validator 2.0.0 Refactoring

Layer / File(s) Summary
Configuration & Documentation Foundation
.php-stan.config.neon, packages/cnpj-val/.pest.config.xml, packages/cnpj-val/CHANGELOG.md, packages/cnpj-val/README.md, packages/cnpj-val/README.pt.md
PHPStan ignore updated; Pest cache/output paths configured; full v2.0.0 changelog and rewritten EN/PT READMEs documenting alphanumeric support and API changes.
Options Configuration & Type Enumeration
packages/cnpj-val/src/CnpjValidatorOptions.php, packages/cnpj-val/src/Enums/CnpjValidationType.php
Adds CnpjValidatorOptions with defaults, overrides merging, magic accessors, and parsing; adds CnpjValidationType enum (Alphanumeric, Numeric) and conversion helpers.
Exception Hierarchy
packages/cnpj-val/src/Exceptions/*.php
New structured exceptions: CnpjValidatorException, CnpjValidatorTypeError, CnpjValidatorInputTypeError, CnpjValidatorOptionsTypeError, CnpjValidatorOptionTypeInvalidException with stored metadata and message formatting.
Validator Implementation & Helper Function
packages/cnpj-val/src/CnpjValidator.php, packages/cnpj-val/src/cnpj-val.php
CnpjValidator rewritten: options-backed constructor, getOptions(), isValid() accepting string
Composer Configuration & Dependencies
packages/cnpj-val/composer.json
PHP requirement bumped to ^8.2; runtime deps updated (adds lacus/cnpj-dv, lacus/utils, removes lacus/cnpj-gen); dev tooling migrated to Pest; PSR-4 autoload namespace moved to Lacus\\BrUtils\\Cnpj\\.
Test Suite Migration to Pest
packages/cnpj-val/tests/Pest.php, packages/cnpj-val/tests/Specs/*.spec.php
Adds Pest bootstrap and comprehensive spec files; removes old PHPUnit test classes/trait and replaces them with focused Pest specs for constructor, isValid behaviors, options merging, and exception messages.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant cnpj_val
  participant CnpjValidator
  participant CnpjValidatorOptions
  participant CnpjCheckDigits
  Client->>cnpj_val: cnpj_val(input, options, type, caseSensitive)
  cnpj_val->>CnpjValidator: isValid(input, options, type, caseSensitive)
  CnpjValidator->>CnpjValidator: toStringInput(input)
  CnpjValidator->>CnpjValidatorOptions: merge per-call overrides
  CnpjValidator->>CnpjValidator: sanitize based on type/case
  CnpjValidator->>CnpjCheckDigits: computeCheckDigits(sanitized)
  CnpjCheckDigits-->>CnpjValidator: digits
  CnpjValidator-->>cnpj_val: bool result
  cnpj_val-->>Client: bool
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • LacusSolutions/br-utils-php#37: Introduces CnpjCheckDigits class that the refactored CnpjValidator delegates check-digit computation to—direct implementation dependency.

Poem

"🐰 I hopped through namespaces, options held tight,
I learned enums by day and exceptions by night,
Tests moved to Pest, docs polished with care,
CNPJ v2 blooms — the warren's now fair! ✨"

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main objective of the pull request: upgrading the cnpj-val package to v2 and adding support for alphanumeric CNPJ format, which aligns with the extensive changes across configuration, documentation, code structure, and tests.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/cnpj-val-v2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@juliolmuller juliolmuller linked an issue May 23, 2026 that may be closed by this pull request
5 tasks
@coderabbitai coderabbitai Bot added the refactoring Non-functional improvements or changes. label May 23, 2026
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/cnpj-val/composer.json`:
- Line 57: The composer.json for package `packages/cnpj-val` still lists the
dependency "lacus/cnpj-gen": "^1.0" but the codebase shows no usage of symbols
like `CnpjGeneratorVerifierDigit` or `Lacus\\CnpjGen`; remove the unused
dependency from the `require` section of `composer.json` in `packages/cnpj-val`,
run `composer update` (or `composer remove lacus/cnpj-gen`) to update
composer.lock and vendor, and run the package tests to confirm nothing breaks;
if any references are found, replace them with the new v2 engine equivalents
before removing.

In `@packages/cnpj-val/README.md`:
- Line 10: Replace the fragile github.com/user-attachments link for the "new
alphanumeric CNPJ format" in README.md with the canonical Receita Federal URL
used elsewhere in the repo (use the exact URL already present in other docs),
and make the identical substitution in README.pt.md so both READMEs point to the
official Receita Federal reference for the alphanumeric CNPJ format.

In `@packages/cnpj-val/src/cnpj-val.php`:
- Line 5: Add a compatibility shim for the old entrypoint by reintroducing the
function in the original namespace Lacus\CnpjVal named cnpj_val that simply
delegates to the moved implementation in Lacus\BrUtils\Cnpj (e.g., call
\Lacus\BrUtils\Cnpj\cnpj_val($cnpjString) or the equivalent new function/class
method). Ensure the shim is declared in namespace Lacus\CnpjVal and accepts the
same signature/return value as the original so existing callers in
packages/cnpj-utils/src/cnpj_utils.php continue to work.

In `@packages/cnpj-val/src/CnpjValidator.php`:
- Around line 91-104: The per-call $options parameter is not validated and
non-array/non-CnpjValidatorOptions values are silently ignored; update the
method that builds $actualOptions (the code calling new CnpjValidatorOptions and
using $options ?? []) to explicitly validate $options: if $options is an
instance of CnpjValidatorOptions use it directly, else if it is an array use it
in the overrides merge, otherwise throw an InvalidArgumentException (or the
repository's standard exception) to match the documented throws contract; keep
usage of toStringInput($cnpjInput) and the existing overrides for 'type' and
'caseSensitive' when constructing or merging into CnpjValidatorOptions.
- Around line 109-117: The sanitization regex currently uses the
case-insensitive flag ('/i') unconditionally, which violates the intended
case-sensitive behavior controlled by $actualOptions->caseSensitive in
CnpjValidator; change the sanitization so that when
$actualOptions->caseSensitive is true you use a case-sensitive pattern (e.g.
'/[^0-9A-Z]/' without the 'i' flag) and only use the '/i' flag when
caseSensitive is false (or rely on the earlier strtoupper branch), applying this
conditional pattern to the non-numeric branch that assigns $sanitizedCnpj (and
keep the numeric branch using '/[^0-9]/').

In `@packages/cnpj-val/src/CnpjValidatorOptions.php`:
- Around line 178-183: The setCaseSensitive method currently coerces any value
to bool with (bool) allowing invalid types like the string "false" to become
true; change validation in setCaseSensitive to accept only actual booleans (or
null) and throw CnpjValidatorOptionsTypeError for any other runtime types, using
self::DEFAULT_CASE_SENSITIVE when $value is null, and then assign the validated
boolean to $this->options['caseSensitive']; reference the setCaseSensitive
method, self::DEFAULT_CASE_SENSITIVE, CnpjValidatorOptionsTypeError, and
$this->options['caseSensitive'] when implementing the check.

In `@packages/cnpj-val/tests/Specs/CnpjValidator.spec.php`:
- Around line 190-208: Update the test description string in the failing spec:
change the 'it' description from "returns `false` for a CNPJ with all digits the
same" to "returns `false` for a CNPJ with all base digits the same" so it
accurately reflects that the test uses repeated 12-digit bases (the $prefix
values) and varies the final check digits; adjust the string passed to the
it(...) call near the anonymous function that uses $prefix and $isValid.

In `@packages/cnpj-val/tests/Specs/Exceptions.spec.php`:
- Line 115: The test constructs CnpjValidatorOptionsTypeError with an invalid
optionName 'hidden', violating the constructor PHPDoc which expects
'caseSensitive'|'type' (and parseCnpjValidationType treats optionName as
'type'); update the failing test cases in the Specs/Exceptions spec to pass a
valid option name (use 'type' or 'caseSensitive' as appropriate) or, if you
intend to allow unknown option names, widen the PHPDoc on
CnpjValidatorOptionsTypeError::__construct (and adjust
CnpjValidatorOptions::parseCnpjValidationType annotations) to accept a broader
string union so PHPStan no longer complains.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 44d23b1c-fcc2-42d3-af0b-f94e805b08df

📥 Commits

Reviewing files that changed from the base of the PR and between 5c4fe38 and ac7287b.

📒 Files selected for processing (23)
  • .php-stan.config.neon
  • packages/cnpj-val/.pest.config.xml
  • packages/cnpj-val/CHANGELOG.md
  • packages/cnpj-val/README.md
  • packages/cnpj-val/README.pt.md
  • packages/cnpj-val/composer.json
  • packages/cnpj-val/src/CnpjValidator.php
  • packages/cnpj-val/src/CnpjValidatorOptions.php
  • packages/cnpj-val/src/Enums/CnpjValidationType.php
  • packages/cnpj-val/src/Exceptions/CnpjValidatorException.php
  • packages/cnpj-val/src/Exceptions/CnpjValidatorInputTypeError.php
  • packages/cnpj-val/src/Exceptions/CnpjValidatorOptionTypeInvalidException.php
  • packages/cnpj-val/src/Exceptions/CnpjValidatorOptionsTypeError.php
  • packages/cnpj-val/src/Exceptions/CnpjValidatorTypeError.php
  • packages/cnpj-val/src/cnpj-val.php
  • packages/cnpj-val/tests/CnpjValidatorClassTest.php
  • packages/cnpj-val/tests/CnpjValidatorFunctionTest.php
  • packages/cnpj-val/tests/CnpjValidatorTestCases.php
  • packages/cnpj-val/tests/Pest.php
  • packages/cnpj-val/tests/Specs/CnpjValidator.spec.php
  • packages/cnpj-val/tests/Specs/CnpjValidatorOptions.spec.php
  • packages/cnpj-val/tests/Specs/Exceptions.spec.php
  • packages/cnpj-val/tests/Specs/cnpj-val.spec.php
💤 Files with no reviewable changes (3)
  • packages/cnpj-val/tests/CnpjValidatorFunctionTest.php
  • packages/cnpj-val/tests/CnpjValidatorClassTest.php
  • packages/cnpj-val/tests/CnpjValidatorTestCases.php

Comment thread packages/cnpj-val/composer.json Outdated
Comment thread packages/cnpj-val/README.md
Comment thread packages/cnpj-val/src/cnpj-val.php
Comment thread packages/cnpj-val/src/CnpjValidator.php Outdated
Comment thread packages/cnpj-val/src/CnpjValidator.php
Comment thread packages/cnpj-val/src/CnpjValidatorOptions.php
Comment thread packages/cnpj-val/tests/Specs/CnpjValidator.spec.php
Comment thread packages/cnpj-val/tests/Specs/Exceptions.spec.php Outdated
juliolmuller and others added 8 commits May 23, 2026 05:05
Fox as per CodeRabbit AI review comment at #43 (comment).

Co-authored-by: CodeRabbit AI <support@coderabbit.ai>
Fox as per CodeRabbit AI review comment at #43 (comment).

Co-authored-by: CodeRabbit AI <support@coderabbit.ai>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
packages/cnpj-val/README.md (1)

10-10: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

issue (if-minor): Use the canonical Receita Federal URL for alphanumeric CNPJ reference.

The github.com/user-attachments/... link is fragile and less durable for long-term documentation. Use the official Receita Federal URL for consistency and reliability.

Proposed diff
-> 🚀 **Full support for the [new alphanumeric CNPJ format](https://github.com/user-attachments/files/23937961/calculodvcnpjalfanaumerico.pdf).**
+> 🚀 **Full support for the [new alphanumeric CNPJ format](https://www.gov.br/receitafederal/pt-br/assuntos/noticias/2023/julho/cnpj-alfa-numerico).**
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cnpj-val/README.md` at line 10, Replace the fragile GitHub
attachment link in the README line containing "🚀 **Full support for the [new
alphanumeric CNPJ format]..." with the official Receita Federal reference URL
for the alphanumeric CNPJ format; update the markdown link target so the visible
text stays the same but the href points to the canonical Receita Federal page
(use the Receita Federal's published URL for the alphanumeric CNPJ
specification).
packages/cnpj-val/README.pt.md (1)

3-3: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

issue (if-minor): Use the canonical Receita Federal URL for alphanumeric CNPJ reference.

For consistency with the English README and long-term documentation durability, replace the github.com/user-attachments/... link with the official Receita Federal URL.

Proposed diff
-> 🚀 **Suporte total ao [novo formato alfanumérico de CNPJ](https://github.com/user-attachments/files/23937961/calculodvcnpjalfanaumerico.pdf).**
+> 🚀 **Suporte total ao [novo formato alfanumérico de CNPJ](https://www.gov.br/receitafederal/pt-br/assuntos/noticias/2023/julho/cnpj-alfa-numerico).**
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cnpj-val/README.pt.md` at line 3, Replace the non-canonical GitHub
link used in the README line that mentions "novo formato alfanumérico de CNPJ"
with the official Receita Federal reference URL; edit the text containing
"https://github.com/user-attachments/files/23937961/calculodvcnpjalfanaumerico.pdf"
and swap it for the canonical Receita Federal link so the README.pt.md uses the
authoritative source.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/cnpj-val/README.md`:
- Line 143: The README sentence "cnpj_val() run the validation on a
`CnpjValidator` instance..." has a subject-verb agreement error; update the
sentence for the `cnpj_val()` symbol to read "cnpj_val() runs the validation on
a `CnpjValidator` instance with the same arguments passed to the function. Use
named arguments for options:" so the verb agrees with the singular subject
`cnpj_val()`.

---

Duplicate comments:
In `@packages/cnpj-val/README.md`:
- Line 10: Replace the fragile GitHub attachment link in the README line
containing "🚀 **Full support for the [new alphanumeric CNPJ format]..." with
the official Receita Federal reference URL for the alphanumeric CNPJ format;
update the markdown link target so the visible text stays the same but the href
points to the canonical Receita Federal page (use the Receita Federal's
published URL for the alphanumeric CNPJ specification).

In `@packages/cnpj-val/README.pt.md`:
- Line 3: Replace the non-canonical GitHub link used in the README line that
mentions "novo formato alfanumérico de CNPJ" with the official Receita Federal
reference URL; edit the text containing
"https://github.com/user-attachments/files/23937961/calculodvcnpjalfanaumerico.pdf"
and swap it for the canonical Receita Federal link so the README.pt.md uses the
authoritative source.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 53b480f5-e954-4db3-b2b6-7c214be1b742

📥 Commits

Reviewing files that changed from the base of the PR and between ac7287b and 0bfca6d.

📒 Files selected for processing (7)
  • packages/cnpj-val/CHANGELOG.md
  • packages/cnpj-val/README.md
  • packages/cnpj-val/README.pt.md
  • packages/cnpj-val/composer.json
  • packages/cnpj-val/src/CnpjValidator.php
  • packages/cnpj-val/src/cnpj-val.php
  • packages/cnpj-val/tests/Specs/Exceptions.spec.php
💤 Files with no reviewable changes (1)
  • packages/cnpj-val/composer.json

Comment thread packages/cnpj-val/README.md Outdated
Fix as per CodeRabbit AI review at #43 (comment).

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@juliolmuller
Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 23, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@juliolmuller juliolmuller merged commit 06a739a into main May 23, 2026
190 of 197 checks passed
@juliolmuller juliolmuller deleted the feat/cnpj-val-v2 branch May 23, 2026 15:35
juliolmuller added a commit to LacusSolutions/br-utils-php_cnpj-val that referenced this pull request May 23, 2026
Fox as per CodeRabbit AI review comment at LacusSolutions/br-utils-php#43 (comment).

Co-authored-by: CodeRabbit AI <support@coderabbit.ai>
juliolmuller added a commit to LacusSolutions/br-utils-php_cnpj-val that referenced this pull request May 23, 2026
Fox as per CodeRabbit AI review comment at LacusSolutions/br-utils-php#43 (comment).

Co-authored-by: CodeRabbit AI <support@coderabbit.ai>
juliolmuller added a commit to LacusSolutions/br-utils-php_cnpj-val that referenced this pull request May 23, 2026
Fix as per CodeRabbit AI review at LacusSolutions/br-utils-php#43 (comment).

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New minor or major features. refactoring Non-functional improvements or changes.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[cnpj-val] Update package to support alphanumeric CNPJ

1 participant