Skip to content

style: improve code formatting and readability across multiple files#28

Merged
konradmichalik merged 1 commit intomainfrom
code-style
Jul 11, 2025
Merged

style: improve code formatting and readability across multiple files#28
konradmichalik merged 1 commit intomainfrom
code-style

Conversation

@konradmichalik
Copy link
Copy Markdown
Contributor

@konradmichalik konradmichalik commented Jul 11, 2025

Summary by CodeRabbit

  • Refactor

    • Improved code readability and consistency through extensive formatting updates across multiple components, including multi-line function signatures, argument lists, and string concatenations.
    • Simplified and centralized configuration application logic.
    • Streamlined control flow in several methods for clarity without altering behavior.
    • Enhanced message formatting for improved maintainability.
  • Style

    • Applied consistent code style to function signatures, parameter lists, and logging statements throughout the codebase.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 11, 2025

Walkthrough

This update refactors several classes across the codebase, focusing on formatting, code style, and minor logic simplifications. Method signatures are reformatted for readability, some control flow is streamlined, and repetitive logic is centralized. No core logic or error handling is altered; all modifications are non-functional and aimed at improving maintainability.

Changes

File(s) Change Summary
src/Command/ValidateTranslationCommand.php Refactored and reformatted method signatures, argument lists, and internal logic for clarity. Simplified validator resolution and class instantiation logic. No functional changes.
src/Config/ConfigFactory.php Centralized repetitive configuration logic into a new private method for setting config options.
src/FileDetector/Collector.php Reformatted method signatures and internal anonymous functions for readability.
src/Parser/AbstractParser.php, src/Parser/ParserRegistry.php, src/Parser/XliffParser.php, Reformatted function signatures, argument lists, and internal logic for readability.
src/Parser/YamlParser.php
src/Result/AbstractValidationResultRenderer.php, src/Result/ValidationResultCliRenderer.php Reformatted method signatures, return types, and internal logic for consistency and clarity.
src/Utility/ClassUtility.php Reformatted static method signatures and internal error logging for better readability.
src/Validator/AbstractValidator.php Reformatted and slightly simplified control flow; improved code readability and used null coalescing assignment.
src/Validator/DuplicateKeysValidator.php, src/Validator/DuplicateValuesValidator.php Reformatted string concatenation and array filtering for improved readability.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ValidateTranslationCommand
    participant Collector
    participant ClassUtility

    User->>ValidateTranslationCommand: Execute command with options
    ValidateTranslationCommand->>Collector: collectFiles(paths, detector, excludePatterns)
    Collector-->>ValidateTranslationCommand: List of files
    ValidateTranslationCommand->>ClassUtility: validateClassInput(interface, type, className)
    ClassUtility-->>ValidateTranslationCommand: Array of class instances
    ValidateTranslationCommand->>ValidateTranslationCommand: resolveValidators(input, config)
    ValidateTranslationCommand-->>User: Outputs validation results
Loading

Possibly related PRs

  • #16: Refactored and improved resolveValidators and validateClassInput in ValidateTranslationCommand.php, which are further modified in this PR.
  • #3: Added new validator support and modified validator selection logic in ValidateTranslationCommand.php, directly related to the refactoring here.
  • #7: Restructured ValidateTranslationCommand.php to use utility classes for validation and file collection, which aligns with the refactoring in this PR.

Poem

A hop and a skip, the code’s now more neat,
With commas and lines, it’s a refactoring treat!
Methods align, and configs are set,
Validators resolve with much less regret.
The rabbit applauds, as code’s now a breeze—
Readable, tidy, and sure to please!
🐇✨

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

🔭 Outside diff range comments (2)
src/FileDetector/Collector.php (1)

31-35: Possible null-logger dereference

$this->logger is nullable yet accessed without the null-safe operator, which will trigger a fatal error when no logger is provided.

-                $this->logger->error('The provided path "'.$path.'" is not a valid directory.');
+                $this->logger?->error('The provided path "'.$path.'" is not a valid directory.');

Apply the same guard to the debug call on line 58, or enforce a non-null logger in the constructor.

src/Command/ValidateTranslationCommand.php (1)

282-305: Whitespace in comma-separated class lists can break validation

When users pass --only "FooValidator, BarValidator" the second entry includes a leading space (" BarValidator"), causing class_exists to fail.

Add trim() to each exploded segment and ignore empty strings.

-        $classNames = str_contains($className, ',') ? explode(',', $className) : [$className];
+        $classNames = array_filter(
+            array_map(
+                'trim',
+                str_contains($className, ',') ? explode(',', $className) : [$className]
+            )
+        );
🧹 Nitpick comments (4)
src/Parser/YamlParser.php (1)

81-85: Regex too restrictive for locale codes

/\.(\w{2})\./ matches only two-character language tags (e.g. “de”), rejecting common variants like en_US or fr-CA. Consider broadening the pattern:

-if (preg_match(
-    '/\.(\w{2})\./',
+if (preg_match(
+    '/\.([a-z]{2}(?:[_-][A-Z]{2})?)\./',

This still captures the primary language in $matches[1] while allowing optional region parts.

src/FileDetector/Collector.php (1)

48-54: Nested array_filter hard to read

Consider extracting the exclusion check into a named function/closure for clarity or using array_diff with a pre-built “to-exclude” list.

src/Result/ValidationResultCliRenderer.php (1)

211-216: Trailing comma requires PHP ≥ 8.0

The trailing comma after $isVerbose = false is valid only from PHP 8.0 upwards.
Ensure your composer.json (or platform.php) already requires PHP 8.0+; otherwise this will be a syntax error on older runtimes.

src/Command/ValidateTranslationCommand.php (1)

295-301: Instantiation purely for validation is heavy

ClassUtility::instantiate() actually creates an object even though you throw the result away.
If you only need validation, call ClassUtility::validateClass() instead to avoid unnecessary object construction and side-effects (e.g. expensive constructors).

This is optional but recommended.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5737516 and 35714a1.

📒 Files selected for processing (13)
  • src/Command/ValidateTranslationCommand.php (5 hunks)
  • src/Config/ConfigFactory.php (1 hunks)
  • src/FileDetector/Collector.php (2 hunks)
  • src/Parser/AbstractParser.php (1 hunks)
  • src/Parser/ParserRegistry.php (1 hunks)
  • src/Parser/XliffParser.php (2 hunks)
  • src/Parser/YamlParser.php (2 hunks)
  • src/Result/AbstractValidationResultRenderer.php (1 hunks)
  • src/Result/ValidationResultCliRenderer.php (3 hunks)
  • src/Utility/ClassUtility.php (2 hunks)
  • src/Validator/AbstractValidator.php (4 hunks)
  • src/Validator/DuplicateKeysValidator.php (2 hunks)
  • src/Validator/DuplicateValuesValidator.php (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (9)
src/Parser/AbstractParser.php (2)
src/Parser/XliffParser.php (1)
  • getSupportedFileExtensions (62-65)
src/Parser/YamlParser.php (1)
  • getSupportedFileExtensions (74-77)
src/Result/AbstractValidationResultRenderer.php (2)
src/Result/ValidationResult.php (1)
  • getOverallResult (52-55)
src/Validator/ResultType.php (1)
  • resolveErrorToCommandExitCode (25-36)
src/Parser/XliffParser.php (2)
src/Parser/AbstractParser.php (1)
  • getFileName (32-35)
src/Parser/ParserInterface.php (1)
  • getFileName (23-23)
src/Parser/YamlParser.php (1)
src/Parser/AbstractParser.php (1)
  • getFileName (32-35)
src/Config/ConfigFactory.php (1)
src/Config/TranslationValidatorConfig.php (1)
  • TranslationValidatorConfig (7-266)
src/Parser/ParserRegistry.php (4)
src/Parser/AbstractParser.php (1)
  • getSupportedFileExtensions (50-50)
src/Parser/XliffParser.php (1)
  • getSupportedFileExtensions (62-65)
src/Parser/YamlParser.php (1)
  • getSupportedFileExtensions (74-77)
src/Parser/ParserInterface.php (1)
  • getSupportedFileExtensions (14-14)
src/Validator/DuplicateKeysValidator.php (1)
src/Parser/AbstractParser.php (1)
  • getFileName (32-35)
src/Command/ValidateTranslationCommand.php (4)
src/FileDetector/Collector.php (2)
  • Collector (11-78)
  • collectFiles (25-77)
src/Config/TranslationValidatorConfig.php (5)
  • TranslationValidatorConfig (7-266)
  • only (131-136)
  • getOnly (151-154)
  • skip (156-161)
  • getSkip (176-179)
src/Validator/ValidatorRegistry.php (2)
  • ValidatorRegistry (7-21)
  • getAvailableValidators (12-20)
src/Utility/ClassUtility.php (2)
  • ClassUtility (9-68)
  • instantiate (11-35)
src/FileDetector/Collector.php (4)
src/Parser/AbstractParser.php (1)
  • getSupportedFileExtensions (50-50)
src/Parser/XliffParser.php (1)
  • getSupportedFileExtensions (62-65)
src/Parser/YamlParser.php (1)
  • getSupportedFileExtensions (74-77)
src/Parser/ParserInterface.php (1)
  • getSupportedFileExtensions (14-14)
🔇 Additional comments (30)
src/Parser/ParserRegistry.php (3)

25-28: LGTM: Improved method signature readability.

The multiline formatting with trailing comma enhances readability and follows modern PHP formatting conventions.


34-38: LGTM: Consistent multiline formatting for in_array call.

The multiline formatting improves readability by making each parameter clearly visible and aligns with the formatting style used throughout the codebase.


43-45: LGTM: Improved logger call formatting.

The multiline formatting enhances readability of the warning message construction.

src/Config/ConfigFactory.php (2)

30-33: LGTM: Clean refactoring that improves maintainability.

The extraction of configuration logic into a dedicated method is a good improvement that reduces code duplication.


35-59: Excellent refactoring that centralizes configuration logic.

The new applyConfigurationSettings method effectively eliminates repetitive code by using a mapping approach. This makes the code more maintainable and easier to extend when adding new configuration options.

The mapping array clearly shows all supported configuration keys and their corresponding setter methods, improving code readability and reducing the chance of errors.

src/Utility/ClassUtility.php (4)

11-16: LGTM: Improved method signature readability.

The multiline parameter formatting with trailing comma enhances readability and follows modern PHP conventions.


23-28: LGTM: Better formatting for sprintf call.

The multiline formatting makes the sprintf parameters more readable, especially with multiple interpolation values.


37-41: LGTM: Consistent multiline parameter formatting.

The method signature formatting aligns with the style used in the instantiate method above.


47-61: LGTM: Improved readability of error logging.

The multiline formatting for both sprintf calls makes the error messages more readable and maintains consistency with the formatting style used throughout the file.

src/Parser/XliffParser.php (2)

14-15: LGTM: Improved docblock formatting.

The multiline exception annotation improves readability by providing better visual separation of the exception description.


69-73: LGTM: Consistent multiline formatting for preg_match call.

The multiline formatting makes the regex pattern and function parameters more readable and aligns with the formatting style used throughout the codebase.

src/Parser/AbstractParser.php (1)

21-25: LGTM: Consistent multiline formatting for in_array call.

The multiline formatting improves readability by making each parameter clearly visible and maintains consistency with the formatting style used in other parser classes like ParserRegistry.php.

src/Result/AbstractValidationResultRenderer.php (1)

129-131: Formatting change looks good

Splitting the chained call across two lines improves readability without affecting behaviour.

src/Parser/YamlParser.php (1)

30-33: PHP version compatibility confirmed
The project’s composer.json specifies PHP ^8.1, so trailing commas in closures are fully supported—no changes required.

src/Validator/DuplicateValuesValidator.php (1)

73-75: Message split is purely cosmetic – looks fine

src/Validator/DuplicateKeysValidator.php (3)

21-23: Good use of multi-line logging call


28-31: Readable callback refactor approved


50-51: String concatenation split improves clarity

src/Result/ValidationResultCliRenderer.php (2)

57-60: Readability improved – no functional impact observed

The reformatted multi-line condition is clearer and keeps the early-exit logic intact.
No additional concerns.


235-238: Guard condition reformatted correctly

Visual style change only; behaviour stays the same. Looks good.

src/Validator/AbstractValidator.php (6)

44-50: Parser resolution split across lines – OK

Pure formatting; call signature unchanged and still lazy-resolves the parser class.
No issues.


56-58: Minor string-concatenation style change

Logging message is unchanged semantically; nothing to flag.


76-82: Verbose file-level debug log – fine

Only style changes. Note that very large projects may produce a lot of output in --verbose, but that’s outside the scope here.


85-95: Early-continue optimisation acknowledged

Skipping empty validation results avoids needless Issue objects – a welcome micro-optimisation.


114-116: Clarifying comment – good

Comment clarifies the extension hook; nothing further.


180-181: Use of null-coalescing assignment operator

??= is concise and safe here. Works on PHP 7.4+. No objections.

src/Command/ValidateTranslationCommand.php (4)

100-102: Help text wrapped – OK

Pure documentation change, improves readability.


156-160: Multiline collectFiles call – OK

No behavioural change; call remains identical.


228-233: Path resolution readable – no functional change

The multiline array_map is fine and still prepends getcwd() for relative paths.


254-276: match expression simplifies branching – looks correct

Logic mirrors the previous if/else chain:

  • --only / config-only takes precedence
  • --skip filters from registry
  • default uses all validators

Edge cases are preserved.
No issues spotted.

@konradmichalik konradmichalik merged commit 0f182c3 into main Jul 11, 2025
28 checks passed
@konradmichalik konradmichalik deleted the code-style 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