Skip to content

build: update phpstan level to 7#35

Merged
konradmichalik merged 4 commits intomainfrom
phpstan-7
Jul 15, 2025
Merged

build: update phpstan level to 7#35
konradmichalik merged 4 commits intomainfrom
phpstan-7

Conversation

@konradmichalik
Copy link
Copy Markdown
Contributor

@konradmichalik konradmichalik commented Jul 14, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling for file and directory operations, preventing potential errors when files or directories are missing or inaccessible.
    • Enhanced robustness in reading and parsing files, including safer handling of current working directory retrieval and file content reading.
    • Added checks to avoid errors when working with non-existent classes or failed parser retrievals.
    • Strengthened validation of schema and configuration files to ensure accessibility before processing.
  • Refactor

    • Updated type annotations and variable assignments for better static analysis and code clarity.
    • Increased static analysis strictness for improved code quality.
    • Added a required PHP extension dependency for libxml.
  • Tests

    • Enhanced test robustness by handling edge cases in file and directory operations.
    • Improved type annotations and assertions in test code for greater reliability and clarity.
    • Added new tests covering error handling in file reading, XML parsing, schema validation, and validator behavior with null or empty inputs.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 14, 2025

Walkthrough

This update removes the PHPStan baseline file, raises PHPStan's analysis level for stricter static analysis, and improves type safety and error handling throughout the codebase. Internal methods are refactored to clarify types, handle edge cases (such as failed file operations), and ensure robust test cleanup. No public APIs or core control flows are changed.

Changes

File(s) Change Summary
phpstan-baseline.neon Removed PHPStan baseline configuration file.
phpstan.neon Increased PHPStan analysis level from 6 to 7.
src/Command/ValidateTranslationCommand.php Improved type annotations and array handling in private methods.
src/Config/ConfigReader.php Added explicit check for file read failure before JSON decoding.
src/FileDetector/Collector.php Added guard for glob returning false before filtering files.
src/Parser/ParserCache.php Changed return type from `ParserInterface
src/Parser/XliffParser.php Added exception if file reading fails in constructor; enabled libxml internal error handling.
src/Result/AbstractValidationResultRenderer.php Added error handling for getcwd() and realpath() failures.
src/Result/ValidationResultCliRenderer.php Added check for class existence before reflection in severity calculation.
src/Result/ValidationRun.php Clarified parser class usage; added check for parser retrieval failure.
src/Utility/PathUtility.php Added error handling for getcwd() and realpath() failures in path normalization.
src/Config/SchemaValidator.php Strengthened JSON schema file existence checks with readability and file type validations.
composer.json Added required PHP extension dependency "ext-libxml": "*" for libxml support.
phpunit.xml Enabled detailed display of PHP notices during tests.
tests/src/Command/ValidateTranslationCommandTest.php Added assertion that decoded JSON output is an array.
tests/src/Config/ConfigFileReaderTest.php Guarded against glob returning false during test cleanup.
tests/src/FileDetector/CollectorTest.php Guarded against glob returning false in recursive directory removal.
tests/src/Parser/JsonParserTest.php Guarded against glob returning false in directory removal; added test for constructor file read failure.
tests/src/Parser/ParserCacheTest.php Added assertions to check parser cache does not return false.
tests/src/Parser/XliffParserTest.php Guarded against glob returning false in directory removal; added tests for constructor errors and fallback behavior.
tests/src/Parser/YamlParserTest.php Guarded against glob returning false in directory removal.
tests/src/Result/OutputTest.php Refined property types; used explicitly typed validator arrays in tests.
tests/src/Result/ValidationResultCliRendererTest.php Refined property and method types; improved mock typing and array annotations.
tests/src/Result/ValidationResultJsonRendererTest.php Refined method and array typing; improved mock typing in helper method.
tests/src/Utility/PathUtilityExtendedTest.php Skipped tests if getcwd() fails.
tests/src/Utility/PathUtilityTest.php Added error handling for getcwd() and glob() failures in setup and directory removal.
tests/src/Validator/AbstractValidatorTest.php Updated logger mock property type; clarified mock usage in test.
tests/src/Validator/DuplicateValuesValidatorTest.php Updated logger mock property type; clarified mock usage in test; added test for handling null values.
tests/src/Validator/PlaceholderConsistencyValidatorTest.php Ensured placeholder extraction test always uses arrays for comparison.
tests/src/Validator/SchemaValidatorTest.php Guarded against glob returning false in directory removal; added tests for schema validator error handling and early returns.
tests/src/Validator/EncodingValidatorTest.php Rewrote test for file read error simulation; added test for empty file content handling.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Command
    participant FileSystem
    participant Parser
    participant Validator
    participant Renderer

    User->>Command: Execute validation
    Command->>FileSystem: Read config/files (with error checks)
    FileSystem-->>Command: Return contents or handle failure
    Command->>Parser: Retrieve parser (check for false)
    Parser-->>Command: Parser instance or false
    Command->>Validator: Run validation (with type-safe class)
    Validator-->>Command: Validation results
    Command->>Renderer: Render results
    Renderer-->>User: Output (with improved error handling)
Loading

Possibly related PRs

  • #26: Introduces a new configuration file reader class, related to this PR's update in ConfigReader for file reading logic.
  • #22: Implements ParserCache with initial type declarations; this PR refines return types and internal variable typing.
  • #10: Modifies parser class resolution logic, related to this PR's internal method improvements in parser handling.

Poem

🐇
The code is now sharper, with types all in line,
No more false globs or missing cwd signs.
Tests clean up smartly, exceptions are caught—
PHPStan’s stricter, baseline forgot!
A hop and a skip, with arrays in array,
This rabbit says: “Type safety? Hooray!”

✨ 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

🧹 Nitpick comments (2)
composer.json (1)

15-18: Consider whether ext-libxml is redundant given ext-simplexml.

ext-simplexml has a hard dependency on ext-libxml, so Composer will already refuse installation when libxml is missing. Keeping the explicit requirement is harmless and can improve clarity, but if you prefer a leaner composer.json, you could drop the line without losing safety.

No action required—just bringing this to your attention.

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

208-235: Consider cross-platform compatibility for empty file test.

The test uses /dev/null which is Unix-specific and may not be available on Windows systems. Consider using a more portable approach.

-            public function testEmptyContent(): array
-            {
-                $content = file_get_contents('/dev/null'); // This returns '' (empty string)
-                if ('' === $content) {
-                    return [];
-                }
-
-                return ['should_not_reach' => 'this'];
-            }
+            public function testEmptyContent(): array
+            {
+                $content = ''; // Simulate empty file content directly
+                if ('' === $content) {
+                    return [];
+                }
+
+                return ['should_not_reach' => 'this'];
+            }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 42712b6 and 337d271.

⛔ Files ignored due to path filters (1)
  • composer.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • composer.json (1 hunks)
  • phpunit.xml (1 hunks)
  • src/Config/SchemaValidator.php (1 hunks)
  • src/Parser/XliffParser.php (1 hunks)
  • tests/src/Config/SchemaValidatorTest.php (1 hunks)
  • tests/src/Parser/JsonParserTest.php (2 hunks)
  • tests/src/Parser/XliffParserTest.php (2 hunks)
  • tests/src/Validator/DuplicateValuesValidatorTest.php (3 hunks)
  • tests/src/Validator/EncodingValidatorTest.php (1 hunks)
  • tests/src/Validator/SchemaValidatorTest.php (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • phpunit.xml
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/Parser/XliffParser.php
  • tests/src/Parser/JsonParserTest.php
  • tests/src/Validator/DuplicateValuesValidatorTest.php
  • tests/src/Parser/XliffParserTest.php
🔇 Additional comments (8)
src/Config/SchemaValidator.php (1)

43-43: Enhanced file validation improves robustness.

The addition of is_readable() and is_file() checks alongside file_exists() provides better error handling for edge cases where a file exists but cannot be read due to permissions or is actually a directory.

tests/src/Validator/SchemaValidatorTest.php (4)

68-72: Robust handling of glob() returning false.

Good defensive programming - when glob() returns false, the directory is immediately removed without attempting to iterate over non-existent files.


249-284: Comprehensive test coverage for file read failure.

The anonymous subclass approach effectively simulates file_get_contents() returning false and verifies proper error logging behavior. The test correctly validates both the logging expectation and the empty result return.


286-328: Well-structured test for unsupported XLIFF version handling.

The test properly simulates the unsupported version scenario and verifies that notice-level logging is used (not error-level) for this specific case, which is appropriate for a non-critical condition.


330-372: Thorough validation exception test coverage.

The test ensures that general validation exceptions (not related to unsupported versions) are properly logged as errors, demonstrating good error categorization logic.

tests/src/Config/SchemaValidatorTest.php (2)

172-196: Effective test for dependency availability check.

The anonymous subclass approach cleanly simulates the scenario where JsonSchema\Validator is not available, ensuring the validate method returns early without throwing exceptions.


198-223: Clever test for file read failure scenario.

Creating a directory instead of a file effectively simulates the read failure condition that the enhanced validation logic now handles. The backup/restore logic ensures test isolation.

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

176-206: Improved file read error simulation.

The rewritten test properly simulates file_get_contents() returning false using an anonymous subclass, with appropriate error logging verification and empty result assertion.

@konradmichalik konradmichalik merged commit 207849f into main Jul 15, 2025
26 of 28 checks passed
@konradmichalik konradmichalik deleted the phpstan-7 branch July 28, 2025 17:13
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