Skip to content

feat: add PlaceholderConsistencyValidator for validating placeholder consistency across translation files#30

Merged
konradmichalik merged 2 commits intomainfrom
placeholder-validator
Jul 11, 2025
Merged

feat: add PlaceholderConsistencyValidator for validating placeholder consistency across translation files#30
konradmichalik merged 2 commits intomainfrom
placeholder-validator

Conversation

@konradmichalik
Copy link
Copy Markdown
Contributor

@konradmichalik konradmichalik commented Jul 11, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a validator that checks for placeholder consistency across translation files, supporting XLIFF and YAML formats.
    • Added a descriptive header to the verbose output of the validation tool.
  • Documentation

    • Updated documentation to list the new placeholder consistency validator and its capabilities.
  • Tests

    • Added comprehensive tests for the new placeholder consistency validator, covering various placeholder styles and scenarios.
    • Updated existing tests to account for the new validator in the registry.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 11, 2025

Walkthrough

A new PlaceholderConsistencyValidator was introduced to check for placeholder consistency across translation files, supporting both XLIFF and YAML formats. Documentation, command help, and the validator registry were updated to include this validator. Comprehensive tests were added to verify its functionality, and existing tests were updated to reflect its inclusion. Additionally, CLI output was enhanced with a header for verbose validation results.

Changes

File(s) Change Summary
README.md Documentation updated to mention the new PlaceholderConsistencyValidator and its capabilities.
src/Command/ValidateTranslationCommand.php Help text updated to list and describe the new validator.
src/Result/ValidationResultCliRenderer.php Added a private method to render a header in verbose CLI output.
src/Validator/PlaceholderConsistencyValidator.php New class implementing placeholder consistency validation across translation files.
src/Validator/ValidatorRegistry.php Registered the new validator in the available validators list.
tests/src/Validator/PlaceholderConsistencyValidatorTest.php New PHPUnit test class covering all aspects of the new validator's behavior and output.
tests/src/Validator/ValidatorRegistryTest.php Updated to expect the new validator in the registry and increased the expected validator count.
tests/src/Fixtures/translations/xliff/fail/locallang.xlf Modified a translation unit to include a placeholder for testing the validator's detection logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant ValidatorRegistry
    participant PlaceholderConsistencyValidator
    participant FileParser

    User->>CLI: Run translation validation command
    CLI->>ValidatorRegistry: Get available validators
    ValidatorRegistry-->>CLI: Return validators (incl. PlaceholderConsistencyValidator)
    CLI->>PlaceholderConsistencyValidator: Validate translation files
    PlaceholderConsistencyValidator->>FileParser: Parse translation files
    FileParser-->>PlaceholderConsistencyValidator: Return parsed keys/values
    PlaceholderConsistencyValidator->>PlaceholderConsistencyValidator: Extract placeholders
    PlaceholderConsistencyValidator->>PlaceholderConsistencyValidator: Compare placeholders across files
    PlaceholderConsistencyValidator-->>CLI: Report issues (warnings) if inconsistencies found
    CLI-->>User: Output validation results
Loading

Poem

🐇
A new validator hops in with care,
Checking placeholders here and there.
Across files it leaps, both YAML and XLF,
Seeking mismatches left and right,
With tests and docs now shining bright—
Translation bunnies, sleep well tonight!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between df0dc7e and 64af24a.

📒 Files selected for processing (4)
  • README.md (1 hunks)
  • src/Command/ValidateTranslationCommand.php (1 hunks)
  • src/Validator/ValidatorRegistry.php (1 hunks)
  • tests/src/Validator/ValidatorRegistryTest.php (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • README.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/Validator/ValidatorRegistry.php
  • tests/src/Validator/ValidatorRegistryTest.php
  • src/Command/ValidateTranslationCommand.php
✨ Finishing Touches
  • 📝 Generate Docstrings

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 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: 1

🧹 Nitpick comments (2)
src/Validator/PlaceholderConsistencyValidator.php (2)

129-165: Consider improving the consistency checking approach.

The current implementation uses the first file as reference, which might not be optimal if the first file contains errors. Consider using a more sophisticated approach like finding the most common placeholder set or allowing explicit reference file specification.

 private function findPlaceholderInconsistencies(array $fileData): array
 {
     if (count($fileData) < 2) {
         return [];
     }
 
     $inconsistencies = [];
     $allPlaceholders = [];
 
-    // Collect all placeholders from all files for this key
+    // Collect all placeholders from all files for this key
     foreach ($fileData as $fileName => $data) {
         $allPlaceholders[$fileName] = $data['placeholders'];
     }
 
-    // Compare placeholders between files
+    // Find the most common placeholder set as reference
     $fileNames = array_keys($allPlaceholders);
-    $referenceFile = $fileNames[0];
+    $placeholderCounts = [];
+    foreach ($allPlaceholders as $placeholders) {
+        $key = serialize(sort($placeholders));
+        $placeholderCounts[$key] = ($placeholderCounts[$key] ?? 0) + 1;
+    }
+    $mostCommonKey = array_key_first($placeholderCounts);
+    $referenceFile = $fileNames[0]; // Fallback to first file
+    foreach ($allPlaceholders as $fileName => $placeholders) {
+        if (serialize(sort($placeholders)) === $mostCommonKey) {
+            $referenceFile = $fileName;
+            break;
+        }
+    }
     $referencePlaceholders = $allPlaceholders[$referenceFile];

270-279: Consider potential issues with overlapping placeholder replacements.

The current string replacement approach might cause issues if one placeholder is a substring of another. Consider using a more robust replacement strategy.

 private function highlightPlaceholders(string $value): string
 {
     $placeholders = $this->extractPlaceholders($value);
+    
+    // Sort by length descending to avoid substring replacement issues
+    usort($placeholders, fn($a, $b) => strlen($b) - strlen($a));
 
     foreach ($placeholders as $placeholder) {
         $value = str_replace($placeholder, "<fg=yellow>{$placeholder}</>", $value);
     }
 
     return $value;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f182c3 and df0dc7e.

📒 Files selected for processing (8)
  • README.md (1 hunks)
  • src/Command/ValidateTranslationCommand.php (1 hunks)
  • src/Result/ValidationResultCliRenderer.php (2 hunks)
  • src/Validator/PlaceholderConsistencyValidator.php (1 hunks)
  • src/Validator/ValidatorRegistry.php (1 hunks)
  • tests/src/Fixtures/translations/xliff/fail/locallang.xlf (1 hunks)
  • tests/src/Validator/PlaceholderConsistencyValidatorTest.php (1 hunks)
  • tests/src/Validator/ValidatorRegistryTest.php (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/Validator/ValidatorRegistry.php (1)
src/Validator/PlaceholderConsistencyValidator.php (1)
  • PlaceholderConsistencyValidator (16-304)
🪛 PHPMD (2.15.0)
src/Validator/PlaceholderConsistencyValidator.php

191-191: Avoid unused local variables such as '$fileInfo'. (Unused Code Rules)

(UnusedLocalVariable)

🔇 Additional comments (14)
tests/src/Fixtures/translations/xliff/fail/locallang.xlf (1)

13-13: LGTM! Appropriate test fixture for placeholder validation.

The addition of the %s placeholder to the test fixture creates a realistic test case for the PlaceholderConsistencyValidator to detect placeholder inconsistencies across translation files.

src/Validator/ValidatorRegistry.php (1)

18-18: LGTM! Validator correctly registered.

The PlaceholderConsistencyValidator is properly added to the available validators registry, maintaining consistency with existing validator registration patterns.

README.md (1)

84-84: LGTM! Documentation accurately describes the new validator.

The documentation entry correctly describes the PlaceholderConsistencyValidator with appropriate function description, supported formats (XLIFF, YAML), and warning level classification.

src/Command/ValidateTranslationCommand.php (1)

107-108: LGTM! Help text accurately describes the new validator.

The help text entry for PlaceholderConsistencyValidator is clear, concise, and follows the established format. The description accurately reflects the validator's functionality and maintains consistency with the ValidatorRegistry ordering.

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

9-9: LGTM! Import statement correctly added.

The import for PlaceholderConsistencyValidator is properly added to support the test assertions.


22-22: LGTM! Test assertion correctly added.

The assertion for PlaceholderConsistencyValidator follows the established pattern and ensures the new validator is properly registered.


24-24: LGTM! Expected count correctly updated.

The expected count is properly updated from 4 to 5 to reflect the addition of the PlaceholderConsistencyValidator.

src/Result/ValidationResultCliRenderer.php (2)

45-55: LGTM! Good UX enhancement.

The header method provides clear context about the tool's purpose and capabilities. The formatting is consistent with Symfony console standards and the usage hint is helpful for users.


120-120: Good integration of the header display.

The placement of the header call at the beginning of verbose output is logical and ensures users get context before seeing detailed validation results.

tests/src/Validator/PlaceholderConsistencyValidatorTest.php (1)

1-441: Excellent comprehensive test coverage.

The test suite thoroughly covers the validator's functionality including:

  • All supported placeholder syntaxes (Symfony, ICU, Twig, printf, Laravel)
  • Edge cases with mixed placeholder styles
  • Consistency validation across multiple files
  • Output formatting and rendering
  • Internal state management
  • Complex scenarios with multiple keys and files

The use of reflection for testing private methods is appropriate and the test structure is well-organized.

src/Validator/PlaceholderConsistencyValidator.php (4)

21-47: LGTM! Clean file processing implementation.

The file processing logic correctly extracts keys and placeholders, with appropriate error handling for invalid files.


82-122: Comprehensive placeholder extraction with good regex patterns.

The method supports multiple placeholder syntaxes with well-crafted regex patterns. The array_unique() call prevents duplicates, which is good practice.


284-287: LGTM! Correct parser support declaration.

The validator correctly declares support for both XLIFF and YAML parsers as intended.


295-303: LGTM! Appropriate configuration for warning-level validation.

The validator correctly returns WARNING result type and enables detailed output, which is appropriate for placeholder consistency checks.

$details = $issue->getDetails();
$files = $details['files'] ?? [];

foreach ($files as $fileName => $fileInfo) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix unused variable.

The variable $fileInfo is declared but never used in the loop body.

-            foreach ($files as $fileName => $fileInfo) {
+            foreach ($files as $fileName => $data) {
                 if (!empty($fileName)) {

Or if you don't need the array values:

-            foreach ($files as $fileName => $fileInfo) {
+            foreach (array_keys($files) as $fileName) {
📝 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
foreach ($files as $fileName => $fileInfo) {
foreach ($files as $fileName => $data) {
if (!empty($fileName)) {
// …rest of loop body…
Suggested change
foreach ($files as $fileName => $fileInfo) {
foreach (array_keys($files) as $fileName) {
if (!empty($fileName)) {
// …rest of loop body…
🧰 Tools
🪛 PHPMD (2.15.0)

191-191: Avoid unused local variables such as '$fileInfo'. (Unused Code Rules)

(UnusedLocalVariable)

🤖 Prompt for AI Agents
In src/Validator/PlaceholderConsistencyValidator.php at line 191, the foreach
loop declares the variable $fileInfo but it is never used in the loop body. To
fix this, remove the unused variable by changing the loop to only iterate over
the keys, for example, use foreach ($files as $fileName) instead of foreach
($files as $fileName => $fileInfo).

# Conflicts:
#	README.md
#	src/Command/ValidateTranslationCommand.php
#	src/Validator/ValidatorRegistry.php
#	tests/src/Validator/ValidatorRegistryTest.php
@konradmichalik konradmichalik merged commit 87154bc into main Jul 11, 2025
28 checks passed
@konradmichalik konradmichalik deleted the placeholder-validator branch July 28, 2025 17:14
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