Skip to content

[cnpj-gen] Analyze and bound recursive retry in CnpjGenerator::generate() #41

@coderabbitai

Description

@coderabbitai

Summary

The generate() method in packages/cnpj-gen/src/CnpjGenerator.php currently retries recursively when CnpjCheckDigits throws a CnpjCheckDigitsException. Since PHP does not optimize tail calls, a prefix/type combination that consistently produces sequences failing check-digit computation could exhaust the call stack without surfacing a meaningful error. Additionally, an unbounded retry could hide systemic failures (e.g., an upstream regression in CnpjCheckDigits) by silently looping indefinitely.

Relevant code (lines ~128–133)

try {
    $cnpjCheckDigits = new CnpjCheckDigits($generatedCnpj);
    $generatedCnpj = $cnpjCheckDigits->cnpj;
} catch (CnpjCheckDigitsException $e) {
    return $this->generate($options, $format, $prefix, $type);
}

Proposed direction

Replace the unbounded recursive retry with an iterative bounded retry (e.g., a for loop with a MAX_RETRIES constant). After exhausting all attempts, re-throw the last CnpjCheckDigitsException (or a new descriptive exception) so failures surface cleanly instead of silently looping or crashing with a stack overflow.

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions