Skip to content

feat: add KeyDepthValidator to warn about excessive nesting depth in translation keys#65

Merged
konradmichalik merged 1 commit intomainfrom
key-depth-validator
Jul 30, 2025
Merged

feat: add KeyDepthValidator to warn about excessive nesting depth in translation keys#65
konradmichalik merged 1 commit intomainfrom
key-depth-validator

Conversation

@konradmichalik
Copy link
Copy Markdown
Contributor

@konradmichalik konradmichalik commented Jul 30, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new translation key depth validator that warns when translation keys are nested beyond a configurable threshold (default is 8 levels).
    • Validator supports various key separators and can be configured via a settings file.
  • Documentation

    • Updated documentation to describe the new key depth validator, including usage instructions, configuration options, and example outputs.
  • Tests

    • Added comprehensive tests and example fixtures to ensure correct detection of deeply nested translation keys and validator configuration.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 30, 2025

Walkthrough

A new translation key nesting depth validator, KeyDepthValidator, has been introduced. Documentation, configuration examples, and tests for this validator were added. The validator is now included in the default set of available validators, and test fixtures demonstrate its detection of deeply nested translation keys across various formats and separators.

Changes

Cohort / File(s) Change Summary
Documentation Updates
README.md, docs/validators.md
Added KeyDepthValidator to the list of validators in the main README and provided detailed documentation, usage examples, configuration options, and guidance for managing key nesting depth in translation files.
Validator Implementation
src/Validator/KeyDepthValidator.php
Introduced the KeyDepthValidator class to check translation key nesting depth, configurable via threshold, supporting multiple key separators, and returning warnings for excessive depth.
Validator Registry
src/Validator/ValidatorRegistry.php
Registered KeyDepthValidator in the list of available validators, making it enabled by default.
Example Fixtures
tests/Fixtures/examples/README.md,
tests/Fixtures/examples/key-depth/deeply-nested.en.yaml,
tests/Fixtures/examples/key-depth/translation-validator.yaml
Added documentation and example files for KeyDepthValidator, including a YAML file with deeply nested keys and a custom validator configuration demonstrating a lowered threshold for testing.
Unit Tests for Validator
tests/src/Validator/KeyDepthValidatorTest.php
Added comprehensive PHPUnit tests covering key depth validation logic, configuration handling, result formatting, and edge cases for the new validator.
Validator Registry Tests
tests/src/Validator/ValidatorRegistryTest.php
Updated tests to assert the presence of KeyDepthValidator in the registry and adjusted the expected validator count accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Validator as KeyDepthValidator
    participant Parser
    participant Logger

    User->>Validator: processFile(Parser)
    Validator->>Parser: getKeys()
    Parser-->>Validator: List of translation keys
    Validator->>Validator: Calculate depth for each key
    alt Any key exceeds threshold
        Validator->>Logger: Log warning (if applicable)
        Validator-->>User: Return warning with violating keys
    else All keys within threshold
        Validator-->>User: Return empty result (no violations)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Poem

In the warren of keys, so deep and profound,
A validator sniffs where the tunnels abound.
With a twitch of its nose, it warns with delight—
“Too many layers! Keep nesting light!”
Now translations are tidy, not lost in the dark,
Thanks to this validator’s diligent mark.
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch key-depth-validator

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@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: 0

🧹 Nitpick comments (1)
docs/validators.md (1)

382-463: Comprehensive validator documentation with minor formatting issues.

The documentation provides excellent coverage of the KeyDepthValidator including:

  • Clear purpose and configuration options
  • Realistic examples and console output
  • Configuration instructions and best practices

However, address these minor formatting issues:

-> [!NOTE]
-> New in version **1.2.0** (https://github.com/move-elevator/composer-translation-validator/pull/65)
+> [!NOTE]  
+> New in version **1.2.0** ([PR #65](https://github.com/move-elevator/composer-translation-validator/pull/65))
-```
+```bash

Consider using "challenging" instead of "hard" for more professional tone:

-Warns when translation keys have excessive nesting depth, helping identify overly complex key structures that may be hard to maintain.
+Warns when translation keys have excessive nesting depth, helping identify overly complex key structures that may be challenging to maintain.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a199da and 3a65f02.

📒 Files selected for processing (9)
  • README.md (1 hunks)
  • docs/validators.md (2 hunks)
  • src/Validator/KeyDepthValidator.php (1 hunks)
  • src/Validator/ValidatorRegistry.php (1 hunks)
  • tests/Fixtures/examples/README.md (1 hunks)
  • tests/Fixtures/examples/key-depth/deeply-nested.en.yaml (1 hunks)
  • tests/Fixtures/examples/key-depth/translation-validator.yaml (1 hunks)
  • tests/src/Validator/KeyDepthValidatorTest.php (1 hunks)
  • tests/src/Validator/ValidatorRegistryTest.php (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
tests/Fixtures/examples/key-depth/translation-validator.yaml (2)
tests/src/Config/TranslationValidatorConfigTest.php (1)
  • TranslationValidatorConfigTest (30-302)
src/Config/TranslationValidatorConfig.php (1)
  • TranslationValidatorConfig (26-285)
src/Validator/ValidatorRegistry.php (1)
src/Validator/KeyDepthValidator.php (1)
  • KeyDepthValidator (34-140)
🪛 LanguageTool
docs/validators.md

[style] ~387-~387: To elevate your writing, try using a synonym here.
Context: ...erly complex key structures that may be hard to maintain. Result: ![Warning](ht...

(HARD_TO)

🪛 markdownlint-cli2 (0.17.2)
docs/validators.md

385-385: Bare URL used

(MD034, no-bare-urls)


425-425: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (19)
tests/Fixtures/examples/README.md (1)

15-15: LGTM!

The addition of the key-depth/ directory entry correctly documents the new KeyDepthValidator example fixtures and maintains alphabetical ordering.

README.md (1)

72-72: LGTM!

The KeyDepthValidator entry is properly documented with a clear description and follows the existing table format. The documentation link aligns with the validator documentation pattern.

tests/Fixtures/examples/key-depth/translation-validator.yaml (1)

1-9: LGTM!

The configuration file is well-structured for demonstration purposes. The lowered threshold of 5 (compared to the default of 8) makes it easier to trigger the validator with example files, and the comments clearly explain the intent.

src/Validator/ValidatorRegistry.php (1)

42-42: LGTM!

The KeyDepthValidator is correctly added to the available validators registry, enabling its discovery and use by the validation framework. The placement maintains logical grouping with other key-related validators.

tests/src/Validator/ValidatorRegistryTest.php (3)

31-31: LGTM!

The import for KeyDepthValidator is correctly added to support the test assertions.


51-51: LGTM!

The assertion correctly verifies that KeyDepthValidator is included in the available validators list.


55-55: LGTM!

The validator count is correctly updated from 10 to 11 to reflect the addition of KeyDepthValidator.

tests/Fixtures/examples/key-depth/deeply-nested.en.yaml (1)

1-69: Excellent test fixture design!

This YAML file provides comprehensive test cases for the KeyDepthValidator with:

  • Clear examples of acceptable nesting (≤8 levels)
  • Realistic examples that exceed the threshold (9-11 levels)
  • Various separator patterns (dots, underscores, hyphens)
  • Helpful comments indicating depth levels for validation

The examples are realistic and will effectively test the validator's behavior across different scenarios.

docs/validators.md (1)

11-11: Good documentation structure maintained.

The new KeyDepthValidator entry is properly integrated into the table of contents and follows the established documentation format.

src/Validator/KeyDepthValidator.php (4)

1-53: Well-structured validator class with good configuration handling.

The class follows established patterns and properly handles:

  • Constructor injection of logger
  • Configuration validation with fallback to defaults
  • Type safety with strict typing

58-96: Solid file processing logic with proper error handling.

The processFile method correctly:

  • Handles invalid files with appropriate logging
  • Processes keys and calculates depths
  • Returns structured violation data
  • Includes helpful pluralization in messages

118-140: Clever depth calculation algorithm with good separator support.

The calculateKeyDepth method effectively:

  • Handles edge cases (empty keys)
  • Supports multiple common separators
  • Uses max depth for mixed separator scenarios
  • Returns intuitive depth values (1-based counting)

The logic correctly identifies the maximum nesting depth when multiple separator types are used in the same key.


106-109: Comprehensive parser support.

Good that the validator supports all major translation file formats (XLIFF, YAML, JSON, PHP), making it widely applicable.

tests/src/Validator/KeyDepthValidatorTest.php (6)

36-70: Excellent core functionality testing.

This test effectively validates the main use case with:

  • Realistic deep nesting examples (9-10 levels)
  • Proper assertion of violation structure
  • Verification of threshold enforcement
  • Clear test data with meaningful key names

97-117: Thorough separator testing with good edge case coverage.

The test validates different separator types and mixed separators, ensuring the algorithm correctly handles real-world key patterns.


119-134: Proper error handling verification.

Good testing of the error path with appropriate logger mock expectations, ensuring invalid files are handled gracefully.


151-179: Comprehensive configuration testing.

Excellent validation of custom threshold configuration with proper boundary testing (exactly at threshold vs exceeding it).


354-385: Thorough private method testing with excellent test cases.

The reflection-based testing of calculateKeyDepth provides comprehensive coverage of:

  • Edge cases (empty strings, single characters)
  • Various separator patterns
  • Mixed separator scenarios
  • Boundary conditions

The test cases are well-designed and cover all realistic scenarios.


273-301: Complete validator interface testing.

Good coverage of all validator interface methods including parser support, result types, and naming.

@konradmichalik konradmichalik merged commit 8b2216d into main Jul 30, 2025
41 checks passed
@konradmichalik konradmichalik deleted the key-depth-validator branch September 7, 2025 13:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant