Skip to content

fix: improve key naming convention detection for dot notation#60

Merged
konradmichalik merged 2 commits intomainfrom
fix-key-naming-convention-validator
Jul 29, 2025
Merged

fix: improve key naming convention detection for dot notation#60
konradmichalik merged 2 commits intomainfrom
fix-key-naming-convention-validator

Conversation

@konradmichalik
Copy link
Copy Markdown
Contributor

@konradmichalik konradmichalik commented Jul 29, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved detection of key naming conventions to correctly distinguish between camelCase keys with dots and true dot.notation keys.
    • Prevented setting dot.notation as a configurable convention, enhancing validation accuracy.
  • New Features

    • Enhanced user guidance with clearer messages and configuration hints during key naming validation.
    • Added suggestions for correcting key formats based on detected naming conventions.
    • Expanded supported output formats to include "github" in validation command.
  • Tests

    • Added extensive tests covering key naming detection, configuration hints, and exception handling for invalid conventions.
    • Verified that dot.notation is excluded from configurable conventions and that related exceptions are properly thrown.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 29, 2025

Walkthrough

The KeyNamingConventionValidator was enhanced to exclude dot.notation from configurable conventions and to improve detection by separately analyzing full keys and their segments. The validator now forbids setting dot.notation as a convention, provides clearer user guidance, and includes conversion suggestions. Extensive tests were added to verify correct handling of dot.notation versus camelCase keys containing dots and to cover new behaviors.

Changes

Cohort / File(s) Change Summary
Key Naming Convention Validator Logic
src/Validator/KeyNamingConventionValidator.php
Added a private boolean property to track configuration hint display per file. The setConvention method now throws an exception if dot.notation is set. Updated convertDotSeparatedKey to accept an optional convention parameter. Introduced private methods isAutoDetectionMode, getConfigurationHint, and suggestKeyConversion to improve user feedback and key conversion suggestions. Enhanced formatIssueMessage to provide detailed guidance and show configuration hints once per file. Refined detectKeyConventions to detect full-key dot.notation matches and merge with segment-based conventions, excluding dot.notation from segment checks. Static method getAvailableConventions excludes dot.notation.
Enum Enhancements for Key Naming Conventions
src/Enum/KeyNamingConvention.php
Modified fromString to reject dot.notation explicitly and throw exceptions listing only configurable conventions. Added getConfigurableConventions to return conventions excluding dot.notation. Updated getAvailableConventions closure to static for consistency.
Test Suite for KeyNamingConventionValidator
tests/src/Validator/KeyNamingConventionValidatorTest.php
Added numerous tests verifying correct detection of camelCase keys with dots vs. true dot.notation keys, reproducing a reported bug scenario, and confirming proper detection of dot.notation keys. Tested configuration hint display behavior and exception throwing when setting dot.notation. Added reflection-based tests for private methods including key conversion and detection logic. Verified enum behavior excluding dot.notation. Removed obsolete tests related to configurable dot.notation. Updated some assertions and test expectations for consistency with new logic.
Command and Config Reader Updates
src/Command/ValidateTranslationCommand.php, src/Config/ConfigReader.php
Added PHPDoc @throws JsonException annotations to methods that may throw this exception. Updated an error message to include "github" as a valid output format option.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Poem

🐇 Through keys with dots and camelCase,
I hop and check each naming place.
No more confusion, clear and bright,
Dot.notation’s out of sight!
Suggestions guide with gentle cheer,
Bugs hop away, the path is clear!
🌿✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-key-naming-convention-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.

@konradmichalik konradmichalik merged commit e3eff1a into main Jul 29, 2025
25 of 26 checks passed
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 47b4b0e and 4515616.

📒 Files selected for processing (5)
  • src/Command/ValidateTranslationCommand.php (2 hunks)
  • src/Config/ConfigReader.php (1 hunks)
  • src/Enum/KeyNamingConvention.php (2 hunks)
  • src/Validator/KeyNamingConventionValidator.php (9 hunks)
  • tests/src/Validator/KeyNamingConventionValidatorTest.php (5 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/Config/ConfigReader.php
  • src/Command/ValidateTranslationCommand.php
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/Validator/KeyNamingConventionValidator.php
  • tests/src/Validator/KeyNamingConventionValidatorTest.php
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/Enum/KeyNamingConvention.php (1)
src/Validator/KeyNamingConventionValidator.php (1)
  • getAvailableConventions (408-424)
🔇 Additional comments (3)
src/Enum/KeyNamingConvention.php (3)

65-78: LGTM! Well-structured validation with clear error messaging.

The enhanced fromString method correctly implements the two-stage validation:

  1. Validates the convention exists as an enum value
  2. Explicitly rejects dot.notation as non-configurable

The error messages appropriately use getConfigurableConventions() to guide users toward valid options, which aligns with the design goal of treating dot.notation as detection-only.


87-88: LGTM! Clean refactoring using static closure.

The method now uses a more concise approach with array_map and a static closure while maintaining the same functionality - returning all enum values as strings including dot.notation.


90-102: LGTM! Well-documented method with clear purpose.

The new getConfigurableConventions method effectively separates the concerns:

  • Provides a clean API for getting user-configurable conventions
  • Excludes dot.notation consistently with the validation logic
  • Includes comprehensive documentation explaining why dot.notation is excluded

The implementation correctly filters out dot.notation while reusing getAvailableConventions() for maintainability.

*
* @return array<string>
*/
public static function getConfigurableConventions(): array
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify consistency with validator's getAvailableConventions method.

There appears to be a potential inconsistency between this enum's approach and the validator's getAvailableConventions method. The relevant code snippet shows the validator manually excluding dot.notation in a loop, while this enum provides a dedicated getConfigurableConventions method.


🏁 Script executed:

#!/bin/bash
# Description: Check if the validator should use the enum's getConfigurableConventions method
# Expected: The validator's getAvailableConventions method might be redundant now

# Search for usage of getAvailableConventions in the validator
rg -A 10 -B 5 "getAvailableConventions" src/Validator/KeyNamingConventionValidator.php

# Search for any other usages of getAvailableConventions that might need updating
rg -A 5 -B 5 "getAvailableConventions" --type php

Length of output: 6299


Use enum’s getConfigurableConventions in the validator for a single source of truth

The validator’s getAvailableConventions currently duplicates the “exclude dot.notation” logic that’s already encapsulated in KeyNamingConvention::getConfigurableConventions(). To avoid divergence and keep things DRY, switch the validator to use the enum’s method directly.

Locations to update:

  • src/Validator/KeyNamingConventionValidator.php: replace the manual loop over KeyNamingConvention::cases() with KeyNamingConvention::getConfigurableConventions().

Proposed diff:

 public static function getAvailableConventions(): array
 {
-    $conventions = [];
-    foreach (KeyNamingConvention::cases() as $convention) {
-        // Exclude dot.notation from configurable conventions
-        if ('dot.notation' === $convention->value) {
-            continue;
-        }
-
-        $conventions[$convention->value] = [
-            'pattern'     => $convention->getPattern(),
-            'description' => $convention->description(),
-        ];
-    }
-    return $conventions;
+    $conventions = [];
+    foreach (KeyNamingConvention::getConfigurableConventions() as $value) {
+        $convention = KeyNamingConvention::from($value);
+        $conventions[$value] = [
+            'pattern'     => $convention->getPattern(),
+            'description' => $convention->description(),
+        ];
+    }
+    return $conventions;
 }

Tests covering getAvailableConventions will continue to pass without modification.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public static function getConfigurableConventions(): array
public static function getAvailableConventions(): array
{
$conventions = [];
foreach (KeyNamingConvention::getConfigurableConventions() as $value) {
$convention = KeyNamingConvention::from($value);
$conventions[$value] = [
'pattern' => $convention->getPattern(),
'description' => $convention->description(),
];
}
return $conventions;
}
🤖 Prompt for AI Agents
In src/Validator/KeyNamingConventionValidator.php, replace the manual iteration
over KeyNamingConvention::cases() in the getAvailableConventions method with a
direct call to KeyNamingConvention::getConfigurableConventions() to reuse the
existing logic and avoid duplication. This change ensures the validator uses the
enum’s single source of truth for configurable conventions.

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