Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor test method names and add doc comments #241

Open
wants to merge 16 commits into
base: 2.x
Choose a base branch
from

Conversation

koriym
Copy link
Member

@koriym koriym commented Feb 22, 2025

+phpstan 2 and vimeo 6 support

Align method docblock with detailed type annotations for improved clarity and stricter type safety. Add a definition and Psalm suppression for better static analysis support.


This pull request enhances the type safety annotations in CacheReader by aligning the method docblock with detailed type annotations. This improvement enhances code clarity and enforces stricter type safety measures. Additionally, a definition and Psalm suppression have been added to enhance static analysis support.

Summary by CodeRabbit

  • Chores

    • Updated continuous integration to use PHP 8.4.
    • Upgraded development and static analysis tool dependencies.
    • Expanded code quality checks.
  • Refactor

    • Enhanced type safety and in-code documentation.
    • Enforced stricter class inheritance controls with final declarations.
    • Applied minor formatting and clean-up improvements.
  • Tests

    • Renamed and documented test methods for better clarity.
    • Adjusted assertions to improve validation and maintainability.

Upgraded multiple packages, including `amphp/amp` to v3.1.0 and related dependencies for compatibility with PHP 8.1. Added several new libraries such as `amphp/cache`, `amphp/parallel`, and `amphp/pipeline`. These updates improve overall functionality, compatibility, and performance of the project.
This commit uniformly applies the #[\Override] attribute to methods that override parent class methods or implement interfaces. This change improves code clarity by explicitly indicating method overrides, aiding in code maintenance and readability.
This change includes the phpstan/phpstan-phpunit package in the vendor-bin/tools/composer.json file. It enhances PHPUnit support for static analysis, improving code quality and test reliability.
Replaced inline `assert` calls with `PHPUnit` assertions for better test readability and robustness. Improved type hints and added missing annotations for clarity and consistency across files. Removed unused statements and comments to simplify the codebase.
Marking classes as final prevents unintended extension, ensuring stricter adherence to design principles and better maintainability. This change reduces risks of unforeseen behavior and increases code clarity.
Unified the usage of attribute syntax across the codebase by replacing #[\Override] with #[Override]. This improves code consistency and adheres to the preferred attribute naming conventions.
Updated the PHP version from 8.3 to 8.4 in both coding standards and static analysis GitHub workflows. This ensures compatibility and aligns with the latest PHP version support.
Introduce @template and @param annotations to improve static analysis
Moved the template annotation below the param tag for better structure and consistency with coding standards. No functional changes introduced.
Renamed test methods for improved clarity and consistency, aligning them with their respective functionalities. Added detailed doc comments to better describe each test's purpose, enhancing code readability and maintainability.
Copy link

sourcery-ai bot commented Feb 22, 2025

Reviewer's Guide by Sourcery

This pull request refactors test method names for improved clarity, adds documentation, and updates the project to PHP 8.4. It also includes several code improvements such as enhanced type hinting, updated annotations, and the addition of static analysis tools. Several other improvements to code readability and maintainability were made throughout the project, including updates to dependencies.

Updated class diagram for Matcher

Loading
classDiagram
  class Matcher {
    +any()
    +annotatedWith($annotationName)
    +subclassesOf($superClass)
    +startsWith($prefix)
    +logicalOr(AbstractMatcher $matcherA, AbstractMatcher $matcherB)
    +logicalAnd(AbstractMatcher $matcherA, AbstractMatcher $matcherB)
    +logicalNot(AbstractMatcher $matcher)
  }
  Matcher --|> MatcherInterface : implements
  Matcher --|> AbstractMatcher : extends
  note for Matcher "Class marked as final"

Updated class diagram for AnyMatcher

Loading
classDiagram
  class AnyMatcher {
    +matchesClass(ReflectionClass $class, array $arguments) : bool
    +matchesMethod(ReflectionMethod $method, array $arguments) : bool
  }
  AnyMatcher --|> AbstractMatcher : extends
  note for AnyMatcher "Class marked as final"

Updated class diagram for NullInterceptor

Loading
classDiagram
  class NullInterceptor {
    +invoke(MethodInvocation $invocation)
  }
  NullInterceptor --|> MethodInterceptor : implements
  note for NullInterceptor "Class marked as final"

Updated class diagram for AnnotatedMatcher

Loading
classDiagram
  class AnnotatedMatcher {
    +matchesClass(ReflectionClass $class, array $arguments) : bool
    +matchesMethod(ReflectionMethod $method, array $arguments) : bool
  }
  AnnotatedMatcher --|> BuiltinMatcher : extends
  note for AnnotatedMatcher "Class marked as final"

Updated class diagram for LogicalAndMatcher

Loading
classDiagram
  class LogicalAndMatcher {
    +matchesClass(ReflectionClass $class, array $arguments) : bool
    +matchesMethod(ReflectionMethod $method, array $arguments) : bool
  }
  LogicalAndMatcher --|> AbstractMatcher : extends
  note for LogicalAndMatcher "Class marked as final"

Updated class diagram for LogicalNotMatcher

Loading
classDiagram
  class LogicalNotMatcher {
    +matchesClass(ReflectionClass $class, array $arguments) : bool
    +matchesMethod(ReflectionMethod $method, array $arguments) : bool
  }
  LogicalNotMatcher --|> AbstractMatcher : extends
  note for LogicalNotMatcher "Class marked as final"

Updated class diagram for LogicalOrMatcher

Loading
classDiagram
  class LogicalOrMatcher {
    +matchesClass(ReflectionClass $class, array $arguments) : bool
    +matchesMethod(ReflectionMethod $method, array $arguments) : bool
  }
  LogicalOrMatcher --|> AbstractMatcher : extends
  note for LogicalOrMatcher "Class marked as final"

Updated class diagram for StartsWithMatcher

Loading
classDiagram
  class StartsWithMatcher {
    +matchesClass(ReflectionClass $class, array $arguments) : bool
    +matchesMethod(ReflectionMethod $method, array $arguments) : bool
  }
  StartsWithMatcher --|> AbstractMatcher : extends
  note for StartsWithMatcher "Class marked as final"

Updated class diagram for SubclassesOfMatcher

Loading
classDiagram
  class SubclassesOfMatcher {
    +matchesClass(ReflectionClass $class, array $arguments) : bool
    +matchesMethod(ReflectionMethod $method, array $arguments) : bool
  }
  SubclassesOfMatcher --|> AbstractMatcher : extends
  note for SubclassesOfMatcher "Class marked as final"

Updated class diagram for CompilationFailedException

Loading
classDiagram
  class CompilationFailedException
  CompilationFailedException --|> LogicException : extends
  note for CompilationFailedException "Class marked as final"

Updated class diagram for InvalidAnnotationException

Loading
classDiagram
  class InvalidAnnotationException
  InvalidAnnotationException --|> InvalidArgumentException : extends
  InvalidAnnotationException --|> ExceptionInterface : implements
  note for InvalidAnnotationException "Class marked as final"

Updated class diagram for InvalidMatcherException

Loading
classDiagram
  class InvalidMatcherException
  InvalidMatcherException --|> InvalidArgumentException : extends
  InvalidMatcherException --|> ExceptionInterface : implements
  note for InvalidMatcherException "Class marked as final"

Updated class diagram for InvalidSourceClassException

Loading
classDiagram
  class InvalidSourceClassException
  InvalidSourceClassException --|> LogicException : extends
  InvalidSourceClassException --|> ExceptionInterface : implements
  note for InvalidSourceClassException "Class marked as final"

Updated class diagram for MultipleClassInOneFileException

Loading
classDiagram
  class MultipleClassInOneFileException
  MultipleClassInOneFileException --|> LogicException : extends
  MultipleClassInOneFileException --|> ExceptionInterface : implements
  note for MultipleClassInOneFileException "Class marked as final"

Updated class diagram for NotWritableException

Loading
classDiagram
  class NotWritableException
  NotWritableException --|> RuntimeException : extends
  NotWritableException --|> ExceptionInterface : implements
  note for NotWritableException "Class marked as final"

File-Level Changes

Change Details Files
Refactored test method names for clarity and added documentation.
  • Renamed test methods to be more descriptive.
  • Added doc comments to explain the purpose of each test method.
tests/ReflectiveMethodInvocationTest.php
Improved code readability and maintainability through refactoring.
  • Adjusted docblock annotations for consistency.
  • Added Psalm annotations to the CacheReader method.
  • Unified attribute syntax by replacing #[\Override] with #[Override].
  • Improved type hints.
  • Replaced inline assert calls with PHPUnit assertions.
  • Added missing annotations.
tests/WeaverTest.php
tests/CompilerTest.php
tests/AopCodeTest.php
tests/ReflectionClassTest.php
sl-src/CacheReader.php
src/Matcher.php
src/TypeString.php
src/Matcher/AnyMatcher.php
src/ReflectionClass.php
tests/VariadicParamsTest.php
Updated project dependencies and PHP version.
  • Updated PHP version in coding standards and workflows to 8.4.
  • Added phpstan/phpstan-phpunit for enhanced static analysis.
  • Upgraded packages for PHP 8.1 compatibility and added new libraries.
vendor-bin/tools/composer.json
src/ReflectiveMethodInvocation.php
tests/AnnotatedMatcherTest.php
src/AnnotatedMatcher.php
src/Bind.php
src/NullInterceptor.php
tests/PointcutTest.php
src/ReflectionMethod.php
tests/Aspect/Fake/FakeMyInterceptor.php
tests/BindTest.php
tests/script/compile.php
tests/script/weave.php
src/BuiltinMatcher.php
src/Compiler.php
src/Matcher/AnnotatedWithMatcher.php
src/Matcher/LogicalAndMatcher.php
src/Matcher/LogicalNotMatcher.php
src/Matcher/LogicalOrMatcher.php
src/Matcher/StartsWithMatcher.php
src/Matcher/SubclassesOfMatcher.php
src/MethodSignatureString.php
.github/workflows/coding-standards.yml
.github/workflows/static-analysis.yml
src/ClassList.php
src/Exception/CompilationFailedException.php
src/Exception/InvalidAnnotationException.php
src/Exception/InvalidArgumentException.php
src/Exception/InvalidMatcherException.php
src/Exception/InvalidSourceClassException.php
src/Exception/LogicException.php
src/Exception/MultipleClassInOneFileException.php
src/Exception/NotWritableException.php
src/InterceptTrait.php
src/Pointcut.php
src/WeavedInterface.php
src/Weaver.php
src/AspectPecl.php
tests/Fake/FakeMethodAnnotationReaderInterceptor.php
vendor-bin/tools/composer.lock

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

codecov bot commented Feb 22, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (a94d2e8) to head (80a277b).
Report is 1 commits behind head on 2.x.

Additional details and impacted files
@@             Coverage Diff             @@
##                 2.x      #241   +/-   ##
===========================================
  Coverage     100.00%   100.00%           
- Complexity       236       237    +1     
===========================================
  Files             29        29           
  Lines            608       608           
===========================================
  Hits             608       608           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

coderabbitai bot commented Feb 22, 2025

Walkthrough

This pull request updates the PHP version parameters in GitHub Actions workflows, enhances type annotations and PHPDoc comments in multiple source files, and enforces class finality by adding the final keyword to several classes and exceptions. In addition, minor internal refactorings are applied—including adjustments in method annotations, removal of redundant assertions, and changes in property declarations. Several test methods are renamed and better documented, and dependency configurations and autoload settings are updated.

Changes

File(s) Change Summary
.github/workflows/coding-standards.yml, .github/workflows/static-analysis.yml Update php_version from 8.3 to 8.4 in workflow configurations.
sl-src/CacheReader.php, src/MethodSignatureString.php, src/TypeString.php, src/Weaver.php Enhance type annotations, update docblocks, and adjust internal logic for clarity and type safety.
src/AnnotatedMatcher.php, src/Exception/CompilationFailedException.php, src/Exception/InvalidAnnotationException.php, src/Exception/InvalidArgumentException.php, src/Exception/InvalidMatcherException.php, src/Exception/InvalidSourceClassException.php, src/Exception/LogicException.php, src/Exception/MultipleClassInOneFileException.php, src/Exception/NotWritableException.php, src/NullInterceptor.php, src/ReflectionClass.php, src/Matcher.php Add the final keyword to class declarations and exceptions to enforce non-inheritability.
src/AspectPecl.php, src/InterceptTrait.php, src/Matcher/AnyMatcher.php, src/WeavedInterface.php, src/Pointcut.php Remove an assertion, add a PHPStan ignore comment, update property annotations, adjust suppression directive, and remove default property values.
tests/... (multiple test files and scripts) Rename test methods, add descriptive docblocks, and replace direct assertions with PHPUnit methods for improved clarity and consistency.
vendor-bin/tools/composer.json, composer.json, phpcs.xml Update dependency version constraints, add new dev dependencies, reformat autoload configuration, and extend code quality checks by including additional directories.

Possibly related PRs

Poem

I'm a rabbit, hopping through the code,
Celebrating changes in each final mode.
Type hints and docblocks now shine bright,
Tests renamed to guide us right.
Dependencies updated with a joyful cheer—
For every commit, I give a happy ear!
🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

Aligned the method docblock with detailed type annotations to improve clarity and enforce stricter type safety. Added a template definition and Psalm suppression for better static analysis support.
@koriym koriym requested a review from NaokiTsuchiya February 22, 2025 11:53
@koriym koriym marked this pull request as ready for review February 22, 2025 11:58
@koriym
Copy link
Member Author

koriym commented Feb 22, 2025

@coderabbitai review
@sourcery-ai review

Copy link
Contributor

@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: 2

🔭 Outside diff range comments (1)
src/Pointcut.php (1)

7-17: 🛠️ Refactor suggestion

Consider making properties readonly to ensure immutability.

The class is marked as @psalm-immutable, but it has public mutable properties. Consider making the properties readonly to ensure true immutability:

 /** @psalm-immutable */
 class Pointcut
 {
     /** @var AbstractMatcher */
-    public $classMatcher;
+    public readonly AbstractMatcher $classMatcher;

     /** @var AbstractMatcher */
-    public $methodMatcher;
+    public readonly AbstractMatcher $methodMatcher;

     /** @var array<MethodInterceptor|class-string<MethodInterceptor>> */
-    public $interceptors;
+    public readonly array $interceptors;
🧹 Nitpick comments (7)
tests/script/compile.php (1)

26-26: Consider adding return type declaration.

While not directly related to the current changes, consider adding a return type declaration to improve type safety further.

-return $compiler->compile(FakeMock::class, $bind);
+/** @return string */
+return $compiler->compile(FakeMock::class, $bind);
src/Weaver.php (1)

57-69: Consider adding explicit error handling for reflection failures.

The newInstanceArgs call could throw a ReflectionException. Consider wrapping this in a try-catch block to provide more meaningful error messages.

 public function newInstance(string $class, array $args): object
 {
     $aopClass = $this->weave($class);
+    try {
         /** @var T $instance */
         $instance = (new ReflectionClass($aopClass))->newInstanceArgs($args);
+    } catch (\ReflectionException $e) {
+        throw new \RuntimeException(
+            sprintf('Failed to create instance of %s: %s', $aopClass, $e->getMessage()),
+            0,
+            $e
+        );
+    }
     if (! $instance instanceof WeavedInterface) {
         return $instance;
     }
src/Exception/InvalidAnnotationException.php (1)

9-9: LGTM! Completes the consistent exception handling pattern.

Making all exception classes final is a solid architectural decision that:

  1. Prevents inheritance misuse
  2. Makes the exception hierarchy more maintainable
  3. Follows PHP 8.x best practices
  4. Improves static analysis capabilities

Consider documenting this pattern in your contributing guidelines to ensure future exception classes follow the same approach.

src/BuiltinMatcher.php (1)

19-20: Consider marking the class as final.

For consistency with other matcher classes in the codebase, consider marking this class as final to prevent inheritance.

-class BuiltinMatcher extends AbstractMatcher
+final class BuiltinMatcher extends AbstractMatcher
tests/ReflectionClassTest.php (1)

18-18: Remove unnecessary PHPStan ignore comment.

The static analysis tool indicates that there is no error to ignore on this line.

-        $this->class = new ReflectionClass(FakeClassTartget::class); // @phpstan-ignore-line
+        $this->class = new ReflectionClass(FakeClassTartget::class);
🧰 Tools
🪛 PHPStan (2.0.3)

18-18: No error to ignore is reported on line 18.

(ignore.unmatchedLine)

sl-src/CacheReader.php (1)

164-169: Consider using return type annotation.

The explicit variable type declaration improves type safety, but consider adding a return type annotation to the closure for even better type safety.

-            function () use ($method, $reflector): array {
+            function () use ($method, $reflector): array<object> {
tests/CompilerTest.php (1)

284-286: Consider using PHPUnit assertion.

Replace the direct assert with a PHPUnit assertion for consistency.

-        assert(is_array(FakeMethodAnnotationReaderInterceptor::$methodAnnotations));
+        $this->assertIsArray(FakeMethodAnnotationReaderInterceptor::$methodAnnotations);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d2460ec and 560ccf8.

⛔ Files ignored due to path filters (1)
  • vendor-bin/tools/composer.lock is excluded by !**/*.lock
📒 Files selected for processing (49)
  • .github/workflows/coding-standards.yml (1 hunks)
  • .github/workflows/static-analysis.yml (1 hunks)
  • sl-src/CacheReader.php (8 hunks)
  • src/AnnotatedMatcher.php (3 hunks)
  • src/AspectPecl.php (0 hunks)
  • src/Bind.php (4 hunks)
  • src/BuiltinMatcher.php (3 hunks)
  • src/ClassList.php (2 hunks)
  • src/Compiler.php (3 hunks)
  • src/Exception/CompilationFailedException.php (1 hunks)
  • src/Exception/InvalidAnnotationException.php (1 hunks)
  • src/Exception/InvalidArgumentException.php (1 hunks)
  • src/Exception/InvalidMatcherException.php (1 hunks)
  • src/Exception/InvalidSourceClassException.php (1 hunks)
  • src/Exception/LogicException.php (1 hunks)
  • src/Exception/MultipleClassInOneFileException.php (1 hunks)
  • src/Exception/NotWritableException.php (1 hunks)
  • src/InterceptTrait.php (1 hunks)
  • src/Matcher.php (7 hunks)
  • src/Matcher/AnnotatedWithMatcher.php (3 hunks)
  • src/Matcher/AnyMatcher.php (4 hunks)
  • src/Matcher/LogicalAndMatcher.php (3 hunks)
  • src/Matcher/LogicalNotMatcher.php (3 hunks)
  • src/Matcher/LogicalOrMatcher.php (3 hunks)
  • src/Matcher/StartsWithMatcher.php (3 hunks)
  • src/Matcher/SubclassesOfMatcher.php (3 hunks)
  • src/MethodSignatureString.php (0 hunks)
  • src/NullInterceptor.php (1 hunks)
  • src/Pointcut.php (1 hunks)
  • src/ReflectionClass.php (6 hunks)
  • src/ReflectionMethod.php (4 hunks)
  • src/ReflectiveMethodInvocation.php (6 hunks)
  • src/TypeString.php (1 hunks)
  • src/WeavedInterface.php (1 hunks)
  • src/Weaver.php (1 hunks)
  • tests/AnnotatedMatcherTest.php (1 hunks)
  • tests/AopCodeTest.php (5 hunks)
  • tests/Aspect/Fake/FakeMyInterceptor.php (1 hunks)
  • tests/BindTest.php (1 hunks)
  • tests/CompilerTest.php (9 hunks)
  • tests/Fake/FakeMethodAnnotationReaderInterceptor.php (1 hunks)
  • tests/PointcutTest.php (1 hunks)
  • tests/ReflectionClassTest.php (2 hunks)
  • tests/ReflectiveMethodInvocationTest.php (2 hunks)
  • tests/VariadicParamsTest.php (1 hunks)
  • tests/WeaverTest.php (3 hunks)
  • tests/script/compile.php (1 hunks)
  • tests/script/weave.php (1 hunks)
  • vendor-bin/tools/composer.json (1 hunks)
💤 Files with no reviewable changes (2)
  • src/AspectPecl.php
  • src/MethodSignatureString.php
✅ Files skipped from review due to trivial changes (10)
  • .github/workflows/coding-standards.yml
  • src/Exception/LogicException.php
  • src/Exception/InvalidSourceClassException.php
  • src/WeavedInterface.php
  • src/Exception/InvalidArgumentException.php
  • src/InterceptTrait.php
  • src/Exception/MultipleClassInOneFileException.php
  • src/Matcher/LogicalAndMatcher.php
  • src/Matcher/SubclassesOfMatcher.php
  • src/Compiler.php
🧰 Additional context used
🪛 PHPStan (2.0.3)
tests/ReflectionClassTest.php

18-18: No error to ignore is reported on line 18.

(ignore.unmatchedLine)

🔇 Additional comments (44)
tests/script/weave.php (2)

7-9: LGTM! Well-structured import statements.

The addition of explicit imports for ClassLoader and assert improves code clarity and maintainability.


13-13: LGTM! Good type safety enhancement.

The assertion ensures type safety by verifying that $loader is an instance of ClassLoader before it's used. This aligns well with the PR's objective of improving type safety.

tests/script/compile.php (2)

7-9: LGTM! Well-structured import statements.

The addition of explicit imports for ClassLoader and assert improves code clarity and maintainability.


13-13: LGTM! Good type safety enhancement.

The assertion ensures type safety by verifying that $loader is an instance of ClassLoader before it's used. This aligns well with the PR's objective of improving type safety.

src/Weaver.php (3)

13-46: LGTM! Well-structured class with proper type safety.

The class is correctly marked as final with immutable properties (readonly), and the constructor parameter uses a precise type hint (non-empty-string).


48-56: LGTM! Excellent use of PHP generics for type safety.

The method signature and documentation properly utilize PHP's template types to ensure type safety through generics.


71-105: LGTM! Well-documented methods with proper type hints.

Both methods have clear implementations with appropriate type hints and error handling.

src/Exception/CompilationFailedException.php (1)

9-9: LGTM! Making the exception class final improves maintainability.

Making exception classes final is a good practice as it prevents potentially incorrect inheritance and makes the exception hierarchy more maintainable.

src/Exception/NotWritableException.php (1)

9-9: LGTM! Consistent with other exception class changes.

Making the exception class final aligns with the project's approach to exception handling and modern PHP practices.

src/Exception/InvalidMatcherException.php (1)

9-9: LGTM! Follows consistent exception handling pattern.

Making the exception class final maintains consistency with other exception classes in the codebase.

src/NullInterceptor.php (1)

7-9: LGTM! Good improvements to type safety.

The changes enhance type safety and code clarity by:

  • Making the class immutable with the final keyword
  • Explicitly marking method overrides with the #[Override] attribute

Also applies to: 12-13

tests/Aspect/Fake/FakeMyInterceptor.php (1)

7-8: LGTM! Good addition of runtime type checking.

The assertion enhances type safety by validating the return type at runtime, complementing the static return type declaration.

Also applies to: 16-16

tests/PointcutTest.php (1)

11-14: LGTM! Good improvements to test documentation.

The changes improve code clarity by:

  • Using a more descriptive test method name
  • Adding clear documentation about the test's purpose
tests/AnnotatedMatcherTest.php (1)

15-19: LGTM! Good improvements to test documentation.

The changes improve code clarity by:

  • Using a more descriptive test method name
  • Adding clear documentation about the test's purpose
tests/VariadicParamsTest.php (1)

11-14: LGTM! Improved test method name and documentation.

The changes enhance clarity by:

  • Using a more descriptive method name that better reflects the test's purpose
  • Adding a clear docblock comment explaining what is being tested
src/Matcher/StartsWithMatcher.php (1)

7-7: LGTM! Added #[Override] attributes to improve clarity.

The addition of #[Override] attributes explicitly indicates that these methods override methods from the parent class, improving code clarity and maintainability.

Also applies to: 19-19, 31-31

src/Matcher/LogicalNotMatcher.php (1)

7-7: LGTM! Added #[Override] attributes to improve clarity.

The addition of #[Override] attributes explicitly indicates that these methods override methods from the parent class, improving code clarity and maintainability.

Also applies to: 19-19, 31-31

tests/Fake/FakeMethodAnnotationReaderInterceptor.php (1)

16-17: LGTM! Good type annotation.

The added PHPDoc comment correctly specifies the type as array<object>|null, which aligns with the property's usage in the invoke method.

src/Matcher/AnnotatedWithMatcher.php (1)

7-7: LGTM! Good use of Override attribute.

The #[Override] attribute correctly marks methods that override parent class methods, improving code clarity and static analysis capabilities.

Also applies to: 19-20, 34-35

src/Matcher/LogicalOrMatcher.php (1)

7-7: LGTM! Good use of Override attribute.

The #[Override] attribute correctly marks methods that override parent class methods, improving code clarity and static analysis capabilities.

Also applies to: 19-20, 36-37

src/BuiltinMatcher.php (1)

7-7: LGTM! Good use of Override attribute.

The #[Override] attribute correctly marks methods that override parent class methods, improving code clarity and static analysis capabilities.

Also applies to: 53-54, 62-63

src/AnnotatedMatcher.php (1)

7-7: LGTM! Good improvements to type safety and inheritance clarity.

The changes enhance code clarity and type safety through:

  • Making the class final to prevent unexpected inheritance
  • Adding #[Override] attributes to clearly indicate method overrides

Also applies to: 14-14, 36-37, 50-51

src/Matcher/AnyMatcher.php (1)

8-8: LGTM! Good improvements to method override clarity.

The changes enhance code clarity through:

  • Adding #[Override] attributes to clearly indicate method overrides
  • Maintaining proper type safety with @var BuiltinMethodsNames annotation

Also applies to: 23-24, 40-41, 51-52

src/ReflectionMethod.php (1)

7-7: LGTM! Good improvements to method override clarity.

The changes enhance code clarity through:

  • Adding #[Override] attributes to clearly indicate method overrides
  • Maintaining existing type safety with psalm annotations

Also applies to: 33-34, 52-53, 72-73

src/Matcher.php (1)

7-7: LGTM! Good improvements to type safety and inheritance clarity.

The changes enhance code clarity and type safety through:

  • Making the class final to prevent unexpected inheritance
  • Adding #[Override] attributes to clearly indicate interface method implementations

Also applies to: 13-13, 20-21, 29-30, 42-43, 57-58, 88-89

tests/ReflectionClassTest.php (1)

21-78: LGTM! Test method names and documentation improvements.

The changes improve test clarity by:

  • Using more descriptive method names that better reflect their purpose
  • Adding clear PHPDoc comments that explain what each test verifies
src/ReflectionClass.php (1)

17-98: LGTM! Enhanced type safety and inheritance clarity.

The changes improve the codebase by:

  • Making the class final to prevent inheritance
  • Adding #[Override] attributes to clearly indicate method overrides
  • Using #[ReturnTypeWillChange] for PHP 8.0+ compatibility
src/ClassList.php (1)

9-81: LGTM! Added Override attribute for clarity.

The addition of the #[Override] attribute to getIterator method clearly indicates it implements the IteratorAggregate interface method.

src/TypeString.php (1)

72-77: LGTM! Improved readability with foreach loop.

The change from array_map to foreach loop:

  • Makes the code more readable and straightforward
  • Properly handles type annotations
  • Maintains the same functionality
src/Bind.php (1)

7-7: LGTM! The #[Override] attributes are correctly placed.

The addition of the #[Override] attributes to the methods implementing BindInterface enhances code clarity and type safety.

Also applies to: 53-53, 79-80, 96-97

tests/WeaverTest.php (1)

16-19: LGTM! Test methods are now more descriptive and better documented.

The renaming of test methods and addition of clear docblocks significantly improves test readability and maintainability.

Also applies to: 30-35, 37-45, 47-54, 56-63, 65-73, 75-82, 84-94, 96-105, 107-114, 116-124, 126-133, 135-142

src/ReflectiveMethodInvocation.php (1)

8-8: LGTM! The #[Override] attributes are correctly placed.

The addition of the #[Override] attributes to the methods implementing MethodInvocation enhances code clarity and type safety.

Also applies to: 77-78, 99-100, 110-111, 129-130, 145-146

tests/ReflectiveMethodInvocationTest.php (1)

28-35: LGTM! Test methods are now more descriptive and better documented.

The renaming of test methods and addition of clear docblocks significantly improves test readability and maintainability.

Also applies to: 37-45, 47-54, 56-63, 65-73, 75-82, 84-94, 96-105, 107-114, 116-124, 126-133, 135-142

tests/BindTest.php (1)

60-69: Add assertions to validate behavior in testToString.

The test method executes code but doesn't verify any behavior. Consider either:

  1. Adding assertions to validate the string representation of the Bind object
  2. Documenting why assertions were removed if this is intentional

Example assertions that could be added:

 public function testToString(): void
 {
     $nullBind = (string) (new Bind());
+    $this->assertNotEmpty($nullBind, 'Empty Bind should have a string representation');

     $interceptors = [new FakeDoubleInterceptor()];
     $pointcut = new Pointcut((new Matcher())->startsWith('Ray'), (new Matcher())->startsWith('get'), $interceptors);
     $this->bind->bind(FakeAnnotateClass::class, [$pointcut]);
     $bindString = (string) $this->bind;
+    $this->assertNotEmpty($bindString, 'Bind with interceptors should have a string representation');
+    $this->assertNotEquals($nullBind, $bindString, 'Bind with interceptors should have different string representation than empty Bind');
 }
sl-src/CacheReader.php (2)

52-72: LGTM! Enhanced type safety and documentation.

The addition of type annotations and the #[Override] attribute improves code clarity and type safety.


74-95: LGTM! Improved type annotations for better type safety.

The enhanced docblock with template type annotations provides better type safety and clarity.

tests/AopCodeTest.php (4)

32-42: LGTM! Improved test method name and documentation.

The renamed method and added docblock clearly describe the test's purpose.


44-54: LGTM! Enhanced test method clarity.

The renamed method and docblock improve understanding of what's being tested.


56-171: LGTM! Comprehensive test documentation.

The detailed docblocks for PHP 8.1 and 8.2 method signatures provide clear context for the tests.


173-180: LGTM! Clear exception test documentation.

The renamed method and docblock clearly indicate the expected exception behavior.

tests/CompilerTest.php (2)

193-196: LGTM! Improved type safety with class-string annotation.

The added type annotation clarifies that $mock is expected to be a valid class name.


208-211: LGTM! Enhanced type safety for annotation arrays.

The added object[] type annotations improve type safety for annotation handling.

Also applies to: 216-219, 257-262, 270-274

.github/workflows/static-analysis.yml (1)

12-13: PHP Version Update Verified

The php_version parameter has been correctly updated to 8.4 in the static analysis workflow configuration. This change aligns with the project's aim to use a consistent PHP version across all GitHub Actions workflows. Please ensure that any other workflows (e.g., coding standards) are similarly updated and fully compatible with PHP 8.4.

vendor-bin/tools/composer.json (1)

5-9: Dependency Versions Successfully Updated

The updates in the "require-dev" section—updating phpmetrics/phpmetrics to ^v3.0.0rc8 || ^v3.0, phpstan/phpstan to ^2.1, vimeo/psalm to ^6.8, and adding phpstan/phpstan-phpunit with version ^2.0—are well-aligned with the shift to PHP 8.4 and the overall goal of bolstering static analysis support. These changes should help improve type safety and compatibility with advanced analysis tools such as PHPStan and Psalm.

As these upgrades introduce new major versions (and even a release candidate), please ensure that:

  • The updated dependencies are fully compatible with your existing codebase and CI/CD pipelines.
  • You run the full test suite and static analysis tools to catch any unforeseen issues related to these dependency changes.

Copy link
Contributor

coderabbitai bot commented Feb 22, 2025

🧩 Analysis chain

@koriym I'll review the changes in this PR.


🏁 Script executed:

#!/bin/bash
# Fetch the PR diff
gh pr diff 241

Length of output: 72346


@koriym The changes look great! The improvements include:

  1. Better test method names that clearly describe their purpose
  2. Enhanced type annotations and docblocks for better code clarity
  3. Added #[Override] attributes for better interface contract enforcement
  4. Upgraded static analysis tools (phpstan 2 and psalm 6)
  5. Made exception classes final for better inheritance control
  6. Added PHP 8.4 support in workflows

The changes improve code quality and maintainability while maintaining backward compatibility.

✅ Actions performed

Comments resolved.


Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Replaced incorrect attribute syntax `[\Override]` with `[Override]` for consistency. Added 'sl-src' directory to PHP CodeSniffer configuration to ensure style checks cover the new directory.
@koriym
Copy link
Member Author

koriym commented Feb 22, 2025

@NaokiTsuchiya Attribute Readerなどでインスタンス化されてしまったりするとクラスが無いことでエラーになってしまうことを防ぐために2d78490を加えました。

Copy link
Contributor

@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 560ccf8 and 15bf9cc.

📒 Files selected for processing (4)
  • composer.json (1 hunks)
  • phpcs.xml (1 hunks)
  • src-compat/Override.php (1 hunks)
  • src/Matcher.php (7 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src-compat/Override.php
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Matcher.php
🧰 Additional context used
🪛 GitHub Actions: Continuous Integration
composer.json

[warning] 1-1: Defining autoload.psr-4 with an empty namespace prefix is a bad idea for performance.

🔇 Additional comments (1)
phpcs.xml (1)

19-19: Directory Check Addition: Validate New "sl-src" Entry.
The new <file>sl-src</file> element adds the sl-src directory to the PHP_CodeSniffer analysis scope. Ensure that this directory exists and follows the same coding standards as src and tests.

The Override.php class was added and registered in the autoload section of composer.json. This ensures the class is loaded automatically if not already defined,(=PHP 8.0-8.2)
The `#[Override]` attribute and its usages have been removed across the codebase, as it is no longer required. The `src-compat/Override.php` file has also been deleted, and references in `composer.json` were updated to reflect the change.
Updated psalm configuration to suppress MissingOverrideAttribute errors. This ensures the codebase avoids unnecessary warnings for missing override attributes, streamlining the static analysis process.
Copy link
Contributor

@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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 440705b and 470c9e1.

📒 Files selected for processing (7)
  • composer.json (1 hunks)
  • sl-src/CacheReader.php (3 hunks)
  • src/AnnotatedMatcher.php (1 hunks)
  • src/Matcher.php (3 hunks)
  • src/Matcher/AnyMatcher.php (1 hunks)
  • src/NullInterceptor.php (1 hunks)
  • src/ReflectionClass.php (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • composer.json
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/NullInterceptor.php
  • src/Matcher/AnyMatcher.php
  • src/AnnotatedMatcher.php
  • src/Matcher.php
🧰 Additional context used
🪛 GitHub Check: sa / Psalm
sl-src/CacheReader.php

[failure] 59-59:
MissingOverrideAttribute: Method Ray\ServiceLocator\CacheReader::getclassannotations should have the "Override" attribute


[failure] 83-83:
MissingOverrideAttribute: Method Ray\ServiceLocator\CacheReader::getclassannotation should have the "Override" attribute

🔇 Additional comments (4)
sl-src/CacheReader.php (2)

48-48: LGTM!

The property assignment formatting change improves code consistency.


158-161: LGTM!

The explicit type declaration for $annotations and split return statement improve code readability and type safety.

src/ReflectionClass.php (2)

12-15: Great job on type safety annotations!

The code demonstrates excellent type safety practices:

  • Uses template annotations for generic type safety
  • Has detailed parameter and return type annotations
  • Includes appropriate psalm suppressions with clear reasons
  • Documents external mutation-free methods

Also applies to: 19-22, 32-40, 53-59, 72-75


16-16:

❓ Verification inconclusive

Breaking Change: Class made final.

Making the class final prevents inheritance, which is a breaking change. However, this aligns with the PR's objective of improving inheritance control and type safety. Since this class already extends \ReflectionClass and implements Reader, preventing further inheritance helps maintain a cleaner inheritance hierarchy.

Let's verify if this class is being extended anywhere in the codebase:


🏁 Script executed:

#!/bin/bash
# Search for any class that extends ReflectionClass
ast-grep --pattern 'class $_ extends ReflectionClass'

Length of output: 55


Attention: Final Class Declaration Verification Needed

The change to mark ReflectionClass as final is an intentional breaking change aimed at improving inheritance control and ensuring robust type safety. An automated search for classes extending ReflectionClass produced no output, suggesting that there are no downstream extensions relying on it. However, the low-confidence output means that you should manually verify that no classes in the codebase extend ReflectionClass.

  • The final keyword introduces a breaking change by disallowing inheritance.
  • Automated search (using ast-grep) did not reveal any subclass extensions, but manual verification is advised.
  • The type safety measures (strict types, template annotations, psalm suppressions) are correctly implemented and need no changes.

Please confirm that no other parts of the codebase rely on subclassing ReflectionClass.

Comment on lines 72 to +83
/**
* {@inheritDoc}
* @param ReflectionClass<object> $class
* @param class-string<TAnnotation> $annotationName
*
* @return TAnnotation|null
*
* @template TAnnotation of object
*
* @psalm-suppress MoreSpecificImplementedParamType
* @psalm-external-mutation-free
*/
public function getClassAnnotation(ReflectionClass $class, $annotationName) // @phpstan-ignore-line
public function getClassAnnotation(ReflectionClass $class, $annotationName)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add #[Override] attribute and LGTM on type improvements!

The enhanced type annotations with template type TAnnotation and detailed parameter/return types improve type safety. However, the method should have an Override attribute as it implements an interface method.

Apply this diff to add the Override attribute:

     /**
      * @param ReflectionClass<object>   $class
      * @param class-string<TAnnotation> $annotationName
      *
      * @return TAnnotation|null
      *
      * @template TAnnotation of object
      *
      * @psalm-suppress MoreSpecificImplementedParamType
      * @psalm-external-mutation-free
      */
+    #[Override]
     public function getClassAnnotation(ReflectionClass $class, $annotationName)
📝 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
/**
* {@inheritDoc}
* @param ReflectionClass<object> $class
* @param class-string<TAnnotation> $annotationName
*
* @return TAnnotation|null
*
* @template TAnnotation of object
*
* @psalm-suppress MoreSpecificImplementedParamType
* @psalm-external-mutation-free
*/
public function getClassAnnotation(ReflectionClass $class, $annotationName) // @phpstan-ignore-line
public function getClassAnnotation(ReflectionClass $class, $annotationName)
/**
* @param ReflectionClass<object> $class
* @param class-string<TAnnotation> $annotationName
*
* @return TAnnotation|null
*
* @template TAnnotation of object
*
* @psalm-suppress MoreSpecificImplementedParamType
* @psalm-external-mutation-free
*/
+ #[Override]
public function getClassAnnotation(ReflectionClass $class, $annotationName)
🧰 Tools
🪛 GitHub Check: sa / Psalm

[failure] 83-83:
MissingOverrideAttribute: Method Ray\ServiceLocator\CacheReader::getclassannotation should have the "Override" attribute

Comment on lines 51 to +59
/**
* {@inheritDoc}
*
* @param ReflectionClass<T> $class
*
* @template T of object
* @psalm-suppress MoreSpecificImplementedParamType
*/
public function getClassAnnotations(ReflectionClass $class) // @phpstan-ignore-line
public function getClassAnnotations(ReflectionClass $class)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add #[Override] attribute and LGTM on type improvements!

The enhanced type annotations with template type T improve type safety. However, the method should have an Override attribute as it implements an interface method.

Apply this diff to add the Override attribute:

     /**
      * {@inheritDoc}
      *
      * @param ReflectionClass<T> $class
      *
      * @template T of object
      * @psalm-suppress MoreSpecificImplementedParamType
      */
+    #[Override]
     public function getClassAnnotations(ReflectionClass $class)
📝 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
/**
* {@inheritDoc}
*
* @param ReflectionClass<T> $class
*
* @template T of object
* @psalm-suppress MoreSpecificImplementedParamType
*/
public function getClassAnnotations(ReflectionClass $class) // @phpstan-ignore-line
public function getClassAnnotations(ReflectionClass $class)
/**
* {@inheritDoc}
*
* @param ReflectionClass<T> $class
*
* @template T of object
* @psalm-suppress MoreSpecificImplementedParamType
*/
#[Override]
public function getClassAnnotations(ReflectionClass $class)
🧰 Tools
🪛 GitHub Check: sa / Psalm

[failure] 59-59:
MissingOverrideAttribute: Method Ray\ServiceLocator\CacheReader::getclassannotations should have the "Override" attribute

Upgraded the PHP version in the Psalm configuration file from 8.3 to 8.4. This aligns the static analysis tool with the project's updated PHP version requirements.
Copy link
Contributor

@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 (1)
psalm.xml (1)

18-20: Addition of Issue Handlers for Psalm
The newly introduced <issueHandlers> section, particularly the suppression of MissingOverrideAttribute warnings, is a pragmatic approach to reduce noise from known issues. However, consider adding an inline comment or documentation explaining the rationale for this suppression to assist future maintainers in understanding its intent.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 470c9e1 and 80a277b.

📒 Files selected for processing (1)
  • psalm.xml (2 hunks)
🔇 Additional comments (1)
psalm.xml (1)

8-8: PHP Version Update
The update of phpVersion from "8.3" to "8.4" is consistent with the changes applied in the corresponding GitHub Actions workflows and static analysis configurations. This change helps ensure that Psalm and other tools run under the intended PHP runtime version.

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.

None yet

2 participants