Skip to content

refactor: phpstan issues#1

Merged
konradmichalik merged 2 commits intomainfrom
phpstan-issues
May 28, 2025
Merged

refactor: phpstan issues#1
konradmichalik merged 2 commits intomainfrom
phpstan-issues

Conversation

@konradmichalik
Copy link
Copy Markdown
Contributor

@konradmichalik konradmichalik commented May 28, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved XML file loading for better compatibility when parsing translation files.
    • Fixed a typo in a validation script command to ensure correct dry-run execution.
  • Documentation

    • Enhanced code documentation with detailed annotations, clarifying input and output types for various methods and interfaces.
  • Chores

    • Updated project dependencies to require the SimpleXML PHP extension.
    • Simplified static analysis configuration and removed all ignored error suppressions for stricter code checks.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented May 28, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes focus on enhancing type safety and documentation by adding PHPDoc annotations to interfaces and classes, refining method signatures, and updating the XML parsing approach in one parser. Configuration files are also updated to require the ext-simplexml PHP extension, simplify PHPStan checks, and remove all ignored errors from the PHPStan baseline.

Changes

File(s) Change Summary
composer.json Added ext-simplexml requirement; simplified PHPStan script command by removing output redirection and format.
phpstan-baseline.neon Removed all ignored errors; ignoreErrors is now an empty array.
src/Command/ValidateTranslationCommand.php Added private collectFiles method with PHPDoc; updated validateFiles method with type hints and PHPDoc.
src/FileDetector/DetectorInterface.php Added PHPDoc to mapTranslationSet method specifying parameter and return types.
src/FileDetector/PrefixFileDetector.php Added PHPDoc to mapTranslationSet and findSourceFiles methods specifying parameter and return types.
src/Parser/ParserInterface.php Added PHPDoc return type annotations to getSupportedFileExtensions and extractKeys methods.
src/Parser/ParserUtility.php Added PHPDoc to resolveAllowedFileExtensions method specifying return type and possible exception.
src/Parser/XliffParser.php Changed XML loading to use file_get_contents + simplexml_load_string; added PHPDoc; refined null return logic.
tests/Build/app/composer.json Fixed typo in script command: corrected --dry-un to --dry-run.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ValidateTranslationCommand
    participant Filesystem
    participant DetectorInterface
    participant ParserInterface

    User->>ValidateTranslationCommand: Execute validation
    ValidateTranslationCommand->>Filesystem: Collect files (collectFiles)
    ValidateTranslationCommand->>DetectorInterface: mapTranslationSet(files)
    DetectorInterface-->>ValidateTranslationCommand: translation sets
    ValidateTranslationCommand->>ParserInterface: extractKeys()
    ParserInterface-->>ValidateTranslationCommand: keys or null
    ValidateTranslationCommand-->>User: Validation result
Loading

Poem

In fields of code where rabbits dwell,
New docs and types now cast their spell.
XML reads with gentle care,
No errors hidden—none to spare!
With SimpleXML now in the mix,
This bunny’s code is sharp and slick.
🐇✨


📜 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 edd6b75 and d78b536.

📒 Files selected for processing (1)
  • tests/Build/app/composer.json (1 hunks)

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 (1)
src/Command/ValidateTranslationCommand.php (1)

122-122: Review the complex nested filtering logic.

While the nested static anonymous functions work correctly, this line has become quite complex and may be difficult to read and maintain.

Consider extracting the filtering logic for better readability:

-            $allFiles = array_filter($allFiles, static fn ($file) => !array_filter($excludePatterns, static fn ($pattern) => fnmatch($pattern, basename($file))));
+            $allFiles = array_filter($allFiles, static function ($file) use ($excludePatterns) {
+                $basename = basename($file);
+                foreach ($excludePatterns as $pattern) {
+                    if (fnmatch($pattern, $basename)) {
+                        return false;
+                    }
+                }
+                return true;
+            });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3eb696f and edd6b75.

📒 Files selected for processing (8)
  • composer.json (2 hunks)
  • phpstan-baseline.neon (1 hunks)
  • src/Command/ValidateTranslationCommand.php (3 hunks)
  • src/FileDetector/DetectorInterface.php (1 hunks)
  • src/FileDetector/PrefixFileDetector.php (2 hunks)
  • src/Parser/ParserInterface.php (1 hunks)
  • src/Parser/ParserUtility.php (1 hunks)
  • src/Parser/XliffParser.php (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/Parser/ParserInterface.php (1)
src/Parser/XliffParser.php (1)
  • getSupportedFileExtensions (56-59)
🔇 Additional comments (15)
composer.json (2)

15-15: LGTM: Adding ext-simplexml dependency.

This addition aligns well with the XML parsing changes mentioned in the summary, ensuring the required extension is explicitly declared.


71-71: LGTM: Simplified PHPStan check command.

Removing the checkstyle output and error-format options makes sense given that the PHPStan baseline has been cleaned up (all ignored errors removed). The simplified command focuses on the essential check with --no-progress for cleaner CI output.

src/Parser/ParserUtility.php (1)

9-13: LGTM: Comprehensive PHPDoc annotation added.

The type annotation array<int, string> accurately describes the return type, and the @throws \ReflectionException correctly documents the potential exception from new \ReflectionClass() on line 20. This improves static analysis and IDE support.

phpstan-baseline.neon (1)

2-2:

Details

✅ Verification successful

LGTM: PHPStan baseline cleared successfully.

Removing all ignored errors from the baseline indicates that the type safety improvements have successfully resolved the PHPStan issues. This is excellent progress toward better code quality.

Let's verify that PHPStan actually passes with the current configuration:


🏁 Script executed:

#!/bin/bash
# Description: Verify PHPStan passes without ignored errors
# Expected: PHPStan should exit with code 0

php vendor/bin/phpstan --no-progress
echo "PHPStan exit code: $?"

Length of output: 236


Approve PHPStan Baseline Cleanup

PHPStan now runs cleanly with no ignored errors (exit code 0). The cleared baseline accurately reflects that all issues have been addressed—no further action is needed.

src/FileDetector/DetectorInterface.php (1)

9-13: LGTM: Essential type documentation for interface method.

The PHPDoc annotations accurately describe the method signature:

  • array<int, string> $files correctly represents a list of file paths
  • array<string, array<int, string>> appropriately describes the return structure mapping language identifiers to file arrays

This documentation is particularly valuable for interface methods as it guides implementers on expected types.

src/Parser/ParserInterface.php (2)

11-13: LGTM: Clear return type documentation added.

The PHPDoc annotation correctly specifies that this method returns an array of strings with integer indices, which aligns with typical file extension arrays.


16-18: LGTM: Appropriate nullable return type documented.

The PHPDoc correctly indicates that extractKeys() can return either an array of strings or null, which is appropriate for a method that might fail to extract keys from invalid files.

src/FileDetector/PrefixFileDetector.php (2)

9-13: LGTM: Accurate type documentation for mapping method.

The PHPDoc correctly documents the complex return type where source files (strings) map to arrays of target files (strings). This improves clarity for static analysis and IDE support.


37-41: LGTM: Clear parameter and return type documentation.

The PHPDoc accurately describes both the input array of file paths and the filtered output array, maintaining consistency with the public method's type annotations.

src/Command/ValidateTranslationCommand.php (3)

100-106: LGTM: Comprehensive type documentation added.

The PHPDoc provides clear type information for all parameters and return value, improving static analysis and developer understanding.


117-117: LGTM: Improved filtering with static anonymous function.

The change to use a static anonymous function is appropriate for performance and follows modern PHP practices. The logic correctly filters files by extension.


128-131: LGTM: Enhanced method signature with proper type annotations.

The added PHPDoc and DetectorInterface type hint improve type safety and make the method dependencies explicit.

src/Parser/XliffParser.php (3)

29-31: LGTM: Consistent return type documentation.

The PHPDoc correctly matches the interface definition and accurately describes the method's behavior.


46-46: LGTM: More explicit empty string handling.

The change from null coalescing operator to explicit empty string check provides clearer intent and potentially better type safety.


53-55: LGTM: Standard return type documentation.

The PHPDoc correctly documents the static method's return type, maintaining consistency with the interface.

throw new \InvalidArgumentException(sprintf('File "%s" is not a valid XLIFF file.', $filePath));
}
$this->xml = @simplexml_load_file($filePath);
$this->xml = @simplexml_load_string(file_get_contents($filePath));
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 the XML loading method change.

The change from simplexml_load_file($filePath) to simplexml_load_string(file_get_contents($filePath)) may affect error handling and performance. Please ensure this change doesn't introduce issues with:

  1. Memory usage for large files
  2. Error reporting differences between the two approaches
  3. Proper handling of XML parsing errors

🏁 Script executed:

#!/bin/bash
# Description: Check for any existing tests or usage patterns that might be affected by the XML loading change

# Search for existing tests of XliffParser
rg -A 10 -B 5 "XliffParser" --type php

# Look for any error handling related to XML parsing
rg -A 5 -B 5 "simplexml_load" --type php

Length of output: 4968


Add tests and validate XML loading in XliffParser

It appears there are no existing tests for XliffParser, so we can’t be certain the switch from

simplexml_load_file($filePath)

to

@simplexml_load_string(file_get_contents($filePath))

behaves correctly under all conditions. Please:

  • Add unit tests for src/Parser/XliffParser.php (constructor):
    • Parsing a well-formed XLIFF file
    • Handling malformed or invalid XML (assert that $this->xml is false or errors are surfaced)
    • (Optional) Memory/performance on a large XLIFF file
  • Review use of the @ operator: ensure suppressing warnings here is intentional. Consider instead using libxml_use_internal_errors() to capture and report XML errors.
  • Update PHPDoc or add inline comments to document any change in error-reporting behavior.
🤖 Prompt for AI Agents
In src/Parser/XliffParser.php at line 25, the change from simplexml_load_file to
using simplexml_load_string with file_get_contents may impact error handling and
memory usage. Add unit tests for the constructor to cover parsing a valid XLIFF
file, handling malformed XML (checking that $this->xml is false or errors are
properly reported), and optionally test with a large file for performance.
Replace the error suppression operator '@' with libxml_use_internal_errors() to
capture XML parsing errors properly and update PHPDoc or add comments to explain
the new error handling approach.

@konradmichalik konradmichalik merged commit b645dd9 into main May 28, 2025
1 check was pending
@konradmichalik konradmichalik deleted the phpstan-issues branch June 28, 2025 09:16
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