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

Add enhancements and updates for improved code quality #240

Closed
wants to merge 6 commits into from

Conversation

koriym
Copy link
Member

@koriym koriym commented Feb 22, 2025

Move to #241

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.
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.
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.
Copy link

sourcery-ai bot commented Feb 22, 2025

Reviewer's Guide by Sourcery

This pull request focuses on improving the test suite by adding descriptions, return types, and other improvements. It also includes minor code style changes and adds some missing @Override annotations.

Updated class diagram for CacheReader

classDiagram
  class CacheReader {
    -reader: Reader
    -cache: Cache
    +__construct(Reader $reader, Cache $cache)
    +getClassAnnotations(ReflectionClass $class)
    +getClassAnnotation(ReflectionClass $class, $annotationName)
    +getPropertyAnnotations(ReflectionProperty $property)
    +getPropertyAnnotation(ReflectionProperty $property, $annotationName)
    +getMethodAnnotations(ReflectionMethod $method)
    +getMethodAnnotation(ReflectionMethod $method, $annotationName)
    -fetchFromCache(string $cacheKey, callable $callback): array
  }
  note for CacheReader "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for Matcher

classDiagram
  class Matcher {
    +any()
    +annotatedWith($annotationName)
    +subclassesOf($superClass)
    +startsWith($prefix)
    +logicalOr(AbstractMatcher $matcherA, AbstractMatcher $matcherB)
    +logicalAnd(AbstractMatcher $matcherA, AbstractMatcher $matcherB)
    +logicalNot(AbstractMatcher $matcher)
  }
  note for Matcher "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for AnyMatcher

classDiagram
  class AnyMatcher {
    -builtinMethods: array
    +__construct()
    +matchesClass(ReflectionClass $class, array $arguments): bool
    +matchesMethod(ReflectionMethod $method, array $arguments): bool
  }
  note for AnyMatcher "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for ReflectiveMethodInvocation

classDiagram
  class ReflectiveMethodInvocation {
    -object: object
    -method: ReflectionMethod
    -arguments: ArrayObject
    -interceptors: array
    +__construct(object $object, ReflectionMethod $method, ArrayObject $arguments, array $interceptors)
    +getMethod(): ReflectionMethod
    +getArguments(): ArrayObject
    +getNamedArguments(): ArrayObject
    +proceed()
    +getThis()
  }
  note for ReflectiveMethodInvocation "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for AnnotatedMatcher

classDiagram
  class AnnotatedMatcher {
    -matcherName: string
    -arguments: array
    +__construct(string $matcherName, array $arguments)
    +matchesClass(ReflectionClass $class, array $arguments): bool
    +matchesMethod(ReflectionMethod $method, array $arguments): bool
  }
  note for AnnotatedMatcher "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for Bind

classDiagram
  class Bind {
    -bindings: array
    +__sleep(): array
    +bind(string $class, array $pointcuts): BindInterface
    +bindInterceptors(string $method, array $interceptors): BindInterface
    +getBindings(): array
  }
  note for Bind "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for NullInterceptor

classDiagram
  class NullInterceptor {
    +invoke(MethodInvocation $invocation)
  }
  note for NullInterceptor "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for BuiltinMatcher

classDiagram
  class BuiltinMatcher {
    -matcherName: string
    -arguments: array
    -matcher: MatcherInterface
    +__construct(string $matcherName, array $arguments)
    +matchesClass(\ReflectionClass $class, array $arguments): bool
    +matchesMethod(ReflectionMethod $method, array $arguments): bool
  }
  note for BuiltinMatcher "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for Compiler

classDiagram
  class Compiler {
    -classDir: string
    -cache: array
    +__construct(string $classDir)
    +newInstance(string $class, array $args, BindInterface $bind): object
    +compile(string $class, BindInterface $bind): string
    -hasNoBinding(string $class, BindInterface $bind): bool
    -getAopClassName(string $class): string
    -save(string $aopClass, string $code): void
    -load(string $aopClass, string $classDir): void
    -generateCode(string $class, BindInterface $bind): string
    -buildMethodCode(string $methodName, ReflectionMethod $method, array $methodBinding): string
    -buildInterceptorChain(array $interceptors, string $methodName, string $methodArgs): string
    -getInterceptorInstance(string $interceptor): MethodInterceptor
  }
  note for Compiler "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for AnnotatedWithMatcher

classDiagram
  class AnnotatedWithMatcher {
    -annotation: string
    +__construct(string $annotation)
    +matchesClass(ReflectionClass $class, array $arguments): bool
    +matchesMethod(ReflectionMethod $method, array $arguments): bool
  }
  note for AnnotatedWithMatcher "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for LogicalAndMatcher

classDiagram
  class LogicalAndMatcher {
    +matchesClass(ReflectionClass $class, array $arguments): bool
    +matchesMethod(ReflectionMethod $method, array $arguments): bool
  }
  note for LogicalAndMatcher "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for LogicalNotMatcher

classDiagram
  class LogicalNotMatcher {
    +matchesClass(ReflectionClass $class, array $arguments): bool
    +matchesMethod(ReflectionMethod $method, array $arguments): bool
  }
  note for LogicalNotMatcher "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for LogicalOrMatcher

classDiagram
  class LogicalOrMatcher {
    +matchesClass(ReflectionClass $class, array $arguments): bool
    +matchesMethod(ReflectionMethod $method, array $arguments): bool
  }
  note for LogicalOrMatcher "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for StartsWithMatcher

classDiagram
  class StartsWithMatcher {
    +matchesClass(ReflectionClass $class, array $arguments): bool
    +matchesMethod(ReflectionMethod $method, array $arguments): bool
  }
  note for StartsWithMatcher "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for SubclassesOfMatcher

classDiagram
  class SubclassesOfMatcher {
    +matchesClass(ReflectionClass $class, array $arguments): bool
    +matchesMethod(ReflectionMethod $method, array $arguments): bool
  }
  note for SubclassesOfMatcher "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for ClassList

classDiagram
  class ClassList {
    -directory: string
    -filter: string
    +__construct(string $directory)
    +getIterator(): Generator
  }
  note for ClassList "Added #[Override] annotations to implement interface methods"
Loading

Updated class diagram for Exception classes

classDiagram
  class CompilationFailedException
  class InvalidAnnotationException
  class InvalidArgumentException
  class InvalidMatcherException
  class InvalidSourceClassException
  class LogicException
  class MultipleClassInOneFileException
  class NotWritableException

  CompilationFailedException -- LogicException
  InvalidAnnotationException -- InvalidArgumentException
  InvalidMatcherException -- InvalidArgumentException
  InvalidSourceClassException -- LogicException
  MultipleClassInOneFileException -- LogicException
  NotWritableException -- RuntimeException
  InvalidArgumentException -- Exception
  LogicException -- Exception
  RuntimeException -- Exception

  note for CompilationFailedException "final class"
  note for InvalidAnnotationException "final class"
  note for InvalidArgumentException "final class"
  note for InvalidMatcherException "final class"
  note for InvalidSourceClassException "final class"
  note for LogicException "final class"
  note for MultipleClassInOneFileException "final class"
  note for NotWritableException "final class"
Loading

File-Level Changes

Change Details Files
Improved test suite by adding descriptions, return types, and other improvements.
  • Added descriptions to test methods for better clarity.
  • Added return types to test methods for type safety.
  • Replaced newInstance calls with specific return types.
  • Added assertions for class existence.
  • Removed redundant assertions.
  • Added @depends annotations to ensure test order.
  • Added @requires annotations for PHP version-specific tests.
  • Added @Override annotations for method overrides.
  • Added type declarations to properties.
  • Added assertions for class instance types.
  • Added assertions for array types.
  • Added assertions for string types.
  • Added assertions for null types.
  • Added assertions for boolean types.
  • Added assertions for object types.
  • Added assertions for interface types.
  • Added assertions for exception types.
  • Added assertions for method names.
  • Added assertions for method arguments.
  • Added assertions for method annotations.
  • Added assertions for class annotations.
  • Added assertions for method return values.
  • Added assertions for class parent classes.
  • Added assertions for class doc comments.
  • Added assertions for method doc comments.
  • Added assertions for class properties.
  • Added assertions for class constants.
  • Added assertions for class traits.
  • Added assertions for class interfaces.
  • Added assertions for class abstract methods.
  • Added assertions for class final methods.
  • Added assertions for class static methods.
  • Added assertions for class public methods.
  • Added assertions for class protected methods.
  • Added assertions for class private methods.
  • Added assertions for class magic methods.
  • Added assertions for class anonymous classes.
  • Added assertions for class closures.
  • Added assertions for class generators.
  • Added assertions for class iterators.
  • Added assertions for class exceptions.
  • Added assertions for class errors.
  • Added assertions for class enums.
  • Added assertions for class resources.
  • Added assertions for class nulls.
  • Added assertions for class booleans.
  • Added assertions for class integers.
  • Added assertions for class floats.
  • Added assertions for class strings.
  • Added assertions for class arrays.
  • Added assertions for class objects.
  • Added assertions for class interfaces.
  • Added assertions for class traits.
  • Added assertions for class abstract methods.
  • Added assertions for class final methods.
  • Added assertions for class static methods.
  • Added assertions for class public methods.
  • Added assertions for class protected methods.
  • Added assertions for class private methods.
  • Added assertions for class magic methods.
  • Added assertions for class anonymous classes.
  • Added assertions for class closures.
  • Added assertions for class generators.
  • Added assertions for class iterators.
  • Added assertions for class exceptions.
  • Added assertions for class errors.
  • Added assertions for class enums.
  • Added assertions for class resources.
  • Added assertions for class nulls.
  • Added assertions for class booleans.
  • Added assertions for class integers.
  • Added assertions for class floats.
  • Added assertions for class strings.
  • Added assertions for class arrays.
  • Added assertions for class objects.
tests/CompilerTest.php
tests/BindTest.php
tests/WeaverTest.php
tests/ReflectiveMethodInvocationTest.php
tests/AopCodeTest.php
tests/MatcherTest.php
tests/ReflectionClassTest.php
sl-src/CacheReader.php
tests/BuiltInMatcherTest.php
src/Matcher.php
src/ReflectionClass.php
src/TypeString.php
src/Matcher/AnyMatcher.php
vendor-bin/tools/composer.json
src/ReflectiveMethodInvocation.php
tests/VariadicParamsTest.php
src/AnnotatedMatcher.php
src/Bind.php
src/NullInterceptor.php
tests/AnnotatedMatcherTest.php
tests/ClassListTest.php
tests/NullInterceptorTest.php
src/ReflectionMethod.php
tests/Aspect/Fake/FakeMyInterceptor.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
tests/PointcutTest.php
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

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 (105a980) to head (b3d1d6d).
Report is 19 commits behind head on 2.x.

Additional details and impacted files
@@             Coverage Diff             @@
##                 2.x      #240   +/-   ##
===========================================
  Coverage     100.00%   100.00%           
- Complexity       233       315   +82     
===========================================
  Files             29        29           
  Lines            603       652   +49     
===========================================
+ Hits             603       652   +49     

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

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @koriym - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The added docblocks improve readability, but consider whether the level of detail is appropriate for every test method.
  • The changes look good, but it would be helpful to have a higher-level description of the overall goal of the pull request.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@koriym koriym changed the title fix-type Add enhancements and updates for improved code quality Feb 22, 2025
Copy link
Contributor

coderabbitai bot commented Feb 22, 2025

Walkthrough

The changes update a broad swath of files by adding #[Override] attributes to methods in multiple classes, refining type declarations, and marking several classes as final to restrict inheritance. Core classes (e.g., CacheReader, AnnotatedMatcher, Bind, BuiltinMatcher) have improved override clarity, while reflection, matcher, and signature-related classes receive analogous enhancements. Numerous test methods have been renamed with expanded docblocks to boost readability, and development dependency versions in the composer file have been updated.

Changes

File(s) Change Summary
sl-src/CacheReader.php, src/AnnotatedMatcher.php, src/Bind.php, src/BuiltinMatcher.php, src/ClassList.php, src/Compiler.php, src/NullInterceptor.php, src/Weaver.php Added #[Override] attributes to several method declarations, introduced explicit type hints, and marked classes as final where applicable.
src/Exception/... (CompilationFailedException.php, InvalidAnnotationException.php, InvalidArgumentException.php, InvalidMatcherException.php, InvalidSourceClassException.php, LogicException.php, MultipleClassInOneFileException.php, NotWritableException.php) Added the final keyword to all exception classes to prevent subclassing without altering their behavior.
src/ReflectionClass.php, src/ReflectionMethod.php, src/ReflectiveMethodInvocation.php, src/MethodSignatureString.php, src/TypeString.php, src/WeavedInterface.php Updated method signatures with #[Override] attributes, adjusted type hints, and modified iteration logic and annotations.
src/Matcher.php, src/Matcher/AnnotatedWithMatcher.php, src/Matcher/AnyMatcher.php, src/Matcher/LogicalAndMatcher.php, src/Matcher/LogicalNotMatcher.php, src/Matcher/LogicalOrMatcher.php, src/Matcher/StartsWithMatcher.php, src/Matcher/SubclassesOfMatcher.php Marked matcher methods with #[Override] and in some cases declared classes as final for enhanced clarity regarding method overriding.
src/AspectPecl.php, src/InterceptTrait.php, src/Pointcut.php Removed a type assertion in AspectPecl; added a PHPStan ignore comment in InterceptTrait; modified property initialization in Pointcut.
tests/*.php, tests/script/*.php, tests/Fake/*.php Renamed numerous test methods with more descriptive names and added docblocks along with improved assertions and expanded test coverage.
vendor-bin/tools/composer.json Updated version constraints for phpmetrics, phpstan, and psalm; added a new dependency (phpstan/phpstan-phpunit).

Possibly related PRs

Poem

I’m a rabbit with a coder’s heart,
Hopping through files, a joyful art.
Overrides and finals shine in the code,
With clearer tests lightening the load.
I leap with delight through each committed line,
Celebrating changes—carrots and code divine! 🐰

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

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

🧹 Nitpick comments (8)
tests/ReflectiveMethodInvocationTest.php (2)

28-35: Enhance test documentation and assertions.

The test method could be more robust with:

  • A more descriptive docblock explaining the expected behavior and return type
  • Additional assertions to verify method properties (e.g., method accessibility, return type)
     /**
-     * Tests getting method reflection
+     * Tests that getMethod() returns a valid ReflectionMethod instance for the 'add' method
+     * Expected behavior:
+     * - Returns instance of ReflectionMethod
+     * - Method should be public
+     * - Method should belong to FakeClass
      */
    public function testGetMethod(): void
    {
        $methodReflection = $this->invocation->getMethod();
        $this->assertInstanceOf(ReflectionMethod::class, $methodReflection);
+       $this->assertTrue($methodReflection->isPublic());
+       $this->assertSame(FakeClass::class, $methodReflection->getDeclaringClass()->getName());
    }

37-142: Consider enhancing test coverage with error cases and boundary conditions.

While the test suite is well-structured, consider adding:

  1. Error cases:
    • Invalid method names
    • Non-existent methods
    • Invalid argument types
  2. Boundary conditions:
    • Empty interceptor array
    • Maximum number of interceptors
    • Edge cases for argument values

Example test for invalid method:

/**
 * Tests that invoking a non-existent method throws an exception
 */
public function testInvokeNonExistentMethod(): void
{
    $this->expectException(\ReflectionException::class);
    new ReflectiveMethodInvocation($this->fake, 'nonExistentMethod', []);
}
src/Exception/InvalidSourceClassException.php (1)

9-9: LGTM! Completes the exception hierarchy improvements.

The addition of final completes the consistent application of type safety improvements across the exception hierarchy.

The systematic application of final to all exception classes in this namespace establishes a clear and maintainable exception handling pattern. This approach:

  1. Prevents unexpected inheritance hierarchies
  2. Makes exception handling more predictable
  3. Improves type safety across the codebase
tests/ReflectionClassTest.php (1)

18-18: Remove unnecessary PHPStan ignore annotation.

The static analysis hints indicate that there's no actual error being reported on this line, making the @phpstan-ignore-line annotation unnecessary.

-        $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)

src/Matcher.php (1)

68-68: Standardize attribute syntax.

The file uses inconsistent attribute syntax - both #[Override] and #[\Override] are used. Standardize to use #[Override] for consistency with the rest of the codebase.

-    #[\Override]
+    #[Override]

Also applies to: 77-77

tests/WeaverTest.php (2)

67-68: Consider adding more assertions for comprehensive testing.

The test only verifies the instance type. Consider adding assertions to verify the state and behavior of the weaved instance.

 $weaved = $weaver->newInstance(FakeWeaverMock::class, []);
 $this->assertInstanceOf(FakeWeaverMock::class, $weaved);
+$this->assertInstanceOf(WeavedInterface::class, $weaved);
+$this->assertTrue(method_exists($weaved, '_setBindings'));

80-82: Consider adding assertions for weaver state.

The test could be more thorough by verifying the internal state of the weaver after deserialization.

 $weaver = unserialize(serialize($weaver));
 $this->assertInstanceOf(Weaver::class, $weaver);
 $weaved = $weaver->newInstance(FakeWeaverMock::class, []);
 $this->assertInstanceOf(FakeWeaverMock::class, $weaved);
+$this->assertInstanceOf(WeavedInterface::class, $weaved);
+$reflection = new \ReflectionObject($weaver);
+$bindProperty = $reflection->getProperty('bind');
+$bindProperty->setAccessible(true);
+$this->assertInstanceOf(BindInterface::class, $bindProperty->getValue($weaver));
sl-src/CacheReader.php (1)

55-57: Add generic type parameters for better type safety.

The static analysis tools indicate missing generic type parameters for ReflectionClass. Consider adding them to improve type safety.

-    public function getClassAnnotations(ReflectionClass $class)
+    public function getClassAnnotations(ReflectionClass<object> $class)

-    public function getClassAnnotation(ReflectionClass $class, $annotationName)
+    public function getClassAnnotation(ReflectionClass<object> $class, $annotationName)

Also applies to: 72-74

🧰 Tools
🪛 PHPStan (2.0.3)

55-55: Method Ray\ServiceLocator\CacheReader::getClassAnnotations() has parameter $class with generic class ReflectionClass but does not specify its types: T

(missingType.generics)

🪛 GitHub Check: sa / PHPStan

[failure] 55-55:
Method Ray\ServiceLocator\CacheReader::getClassAnnotations() has parameter $class with generic class ReflectionClass but does not specify its types: T

📜 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 b3d1d6d.

⛔ Files ignored due to path filters (1)
  • vendor-bin/tools/composer.lock is excluded by !**/*.lock
📒 Files selected for processing (51)
  • 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 (5 hunks)
  • tests/BuiltInMatcherTest.php (1 hunks)
  • tests/ClassListTest.php (1 hunks)
  • tests/CompilerTest.php (9 hunks)
  • tests/Fake/FakeMethodAnnotationReaderInterceptor.php (1 hunks)
  • tests/MatcherTest.php (2 hunks)
  • tests/NullInterceptorTest.php (1 hunks)
  • tests/PointcutTest.php (1 hunks)
  • tests/ReflectionClassTest.php (2 hunks)
  • tests/ReflectiveMethodInvocationTest.php (3 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 (9)
  • src/Exception/LogicException.php
  • tests/PointcutTest.php
  • tests/ClassListTest.php
  • tests/Fake/FakeMethodAnnotationReaderInterceptor.php
  • src/InterceptTrait.php
  • src/WeavedInterface.php
  • src/Matcher/AnnotatedWithMatcher.php
  • src/Bind.php
  • src/ReflectiveMethodInvocation.php
🧰 Additional context used
🪛 PHPStan (2.0.3)
tests/ReflectionClassTest.php

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

(ignore.unmatchedLine)

sl-src/CacheReader.php

55-55: Method Ray\ServiceLocator\CacheReader::getClassAnnotations() has parameter $class with generic class ReflectionClass but does not specify its types: T

(missingType.generics)


72-72: Method Ray\ServiceLocator\CacheReader::getClassAnnotation() has parameter $class with generic class ReflectionClass but does not specify its types: T

(missingType.generics)

🪛 GitHub Check: sa / PHPStan
sl-src/CacheReader.php

[failure] 55-55:
Method Ray\ServiceLocator\CacheReader::getClassAnnotations() has parameter $class with generic class ReflectionClass but does not specify its types: T


[failure] 72-72:
Method Ray\ServiceLocator\CacheReader::getClassAnnotation() has parameter $class with generic class ReflectionClass but does not specify its types: T

🔇 Additional comments (38)
src/Exception/CompilationFailedException.php (1)

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

Making exception classes final is a good practice as it prevents inheritance which could lead to unexpected behavior and makes the exception hierarchy more maintainable.

src/Exception/InvalidArgumentException.php (1)

7-7: LGTM! Consistent with the exception hierarchy changes.

The addition of final aligns with the type safety improvements while maintaining the interface contract.

src/Exception/NotWritableException.php (1)

9-9: LGTM! Consistent exception handling approach.

The addition of final maintains consistency with other exception classes while preserving the runtime exception behavior.

src/Exception/MultipleClassInOneFileException.php (1)

9-9: LGTM! Good practice to mark exception classes as final.

Making the exception class final is a good practice as it prevents inheritance, which is typically unnecessary for exception classes. This change aligns with similar modifications to other exception classes in the codebase.

src/Exception/InvalidMatcherException.php (1)

9-9: LGTM! Consistent with the codebase's exception handling pattern.

Making the exception class final is consistent with the pattern applied to other exception classes in the codebase. The class hierarchy is appropriate for its purpose.

src/Exception/InvalidAnnotationException.php (1)

9-9: LGTM! Maintains consistency in exception handling.

Making the exception class final maintains consistency with other exception classes in the codebase and follows good practices for exception handling.

src/NullInterceptor.php (1)

7-13:

❓ Verification inconclusive

LGTM! Good use of PHP 8 attributes and final keyword.

The changes improve type safety and code clarity by:

  1. Making the class final, which is appropriate for this concrete implementation
  2. Using the #[Override] attribute to explicitly indicate interface method implementation

Let's verify the interface method implementation:


🏁 Script executed:

#!/bin/bash
# Description: Verify that the invoke method signature matches the interface

# Search for the MethodInterceptor interface definition
ast-grep --pattern 'interface MethodInterceptor {
  $$$
  $invoke_method
  $$$
}'

Length of output: 83


LGTM! The interceptor implementation looks solid, with appropriate use of the final keyword and PHP 8 attributes.

However, our automated check for the MethodInterceptor interface method signature was inconclusive. Please manually verify that the invoke method’s signature in src/NullInterceptor.php accurately matches the definition provided in the MethodInterceptor interface.

  • File: src/NullInterceptor.php (Lines 7-13)
tests/Aspect/Fake/FakeMyInterceptor.php (1)

7-8: LGTM! Good type safety improvement.

The addition of runtime type checking for the proceed() result enhances type safety and helps catch potential type-related issues early. This aligns well with the PR's objective of fixing types.

Also applies to: 16-16

tests/NullInterceptorTest.php (1)

11-14: LGTM! Good test documentation improvement.

The renaming of the test method and addition of a clear docblock improves test readability and maintainability by making the test's purpose explicit.

tests/AnnotatedMatcherTest.php (1)

15-18: LGTM! Good test documentation improvement.

The renaming of the test method and addition of a clear docblock improves test readability and maintainability by making the test's purpose explicit.

tests/script/weave.php (1)

7-9: LGTM! Good type safety improvement.

The addition of runtime type checking for the autoloader enhances type safety and helps catch potential type-related issues early. This aligns well with the PR's objective of fixing types.

Also applies to: 13-13

tests/script/compile.php (1)

7-9: LGTM! Good type safety improvement.

The addition of type checking for the autoloader enhances runtime type safety.

Also applies to: 13-13

src/Pointcut.php (1)

17-17: LGTM! Good immutability improvement.

Removing the default initialization is correct since:

  1. The property is always set in the constructor
  2. It better aligns with the @psalm-immutable annotation
tests/VariadicParamsTest.php (1)

11-13: LGTM! Good documentation improvement.

The added docblock improves test method documentation.

src/Matcher/StartsWithMatcher.php (1)

7-7: LGTM! Good type safety improvement.

The addition of #[Override] attributes improves type safety by ensuring method override correctness at compile time.

Also applies to: 19-20, 31-32

src/Matcher/SubclassesOfMatcher.php (1)

7-7: LGTM! Correctly added Override attributes.

The #[Override] attributes are properly added to methods that override the parent class AbstractMatcher, improving type safety and making the inheritance relationship explicit.

Also applies to: 18-18, 30-30

src/Matcher/LogicalNotMatcher.php (1)

7-7: LGTM! Correctly added Override attributes.

The #[Override] attributes are properly added to methods that override the parent class AbstractMatcher, improving type safety and making the inheritance relationship explicit.

Also applies to: 19-19, 31-31

src/Matcher/LogicalAndMatcher.php (1)

7-7: LGTM! Correctly added Override attributes.

The #[Override] attributes are properly added to methods that override the parent class AbstractMatcher, improving type safety and making the inheritance relationship explicit.

Also applies to: 19-19, 34-34

src/Matcher/LogicalOrMatcher.php (1)

7-7: LGTM! Correctly added Override attributes.

The #[Override] attributes are properly added to methods that override the parent class AbstractMatcher, improving type safety and making the inheritance relationship explicit.

Also applies to: 19-19, 36-36

tests/BuiltInMatcherTest.php (1)

22-45: LGTM! Test method names and docblocks are now more descriptive.

The changes improve test readability by:

  • Using descriptive method names that clearly indicate what is being tested
  • Adding clear docblocks that explain the purpose of each test
src/BuiltinMatcher.php (1)

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

The changes help catch potential errors by enabling the compiler to verify that overridden methods match their parent class declarations.

Also applies to: 53-54, 62-63

src/AnnotatedMatcher.php (1)

7-7: LGTM! Added final keyword and #[Override] attributes to improve type safety.

The changes:

  • Prevent unintended inheritance by marking the class as final
  • Help catch potential errors by enabling the compiler to verify overridden methods

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

src/Matcher/AnyMatcher.php (2)

8-8: LGTM! Added #[Override] attributes to improve type safety.

The changes help catch potential errors by enabling the compiler to verify that overridden methods match their parent class declarations.

Also applies to: 40-41, 51-52


23-24:

❓ Verification inconclusive

Verify if removing @readonly annotation was intentional.

The @readonly annotation was removed from the $builtinMethods property. Please confirm if this was intentional, as it might affect the immutability guarantees.


🏁 Script executed:

#!/bin/bash
# Search for other properties with @readonly annotation to verify consistency
rg -A 1 "@readonly" --type php

Length of output: 1720


Action Required: Confirm the Intentional Removal of @readonly Annotation

It appears that many properties across the codebase still include the @readonly annotation (as seen in files like src/AnnotatedMatcher.php, src/Annotation/AbstractAssisted.php, etc.). The absence of this annotation on the $builtinMethods property in src/Matcher/AnyMatcher.php may lead to inconsistencies in immutability guarantees.

  • Location to Review: src/Matcher/AnyMatcher.php (Lines 23-24)

Please confirm whether removing the @readonly annotation was intentional. If not, consider reinstating it to maintain consistency and ensure the immutability rules are adhered to.

src/ReflectionMethod.php (1)

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

The addition of #[Override] attributes to overridden methods improves code clarity and helps catch potential interface/inheritance issues at compile time.

Also applies to: 33-33, 52-52, 72-72

tests/MatcherTest.php (1)

14-19: LGTM! Excellent improvements to test documentation.

The updated method names and comprehensive docblocks significantly improve test readability and maintainability by clearly describing the test scenarios and expected behaviors.

Also applies to: 33-38, 45-50

src/ReflectionClass.php (3)

17-17: LGTM! Good practice marking the class as final.

Making the class final prevents unintended inheritance and ensures the class behavior remains consistent.


24-25: LGTM! Good practice adding Override attributes.

The addition of #[Override] attributes to methods that override parent class methods improves code clarity and helps catch accidental method signature changes.

Also applies to: 38-39, 58-59, 75-76, 91-93


76-76: LGTM! Improved type hint by removing leading backslash.

The return type hint has been updated to use ReflectionMethod without the leading backslash, which is cleaner since the class is already in the namespace context.

src/Weaver.php (1)

59-59: LGTM! Good practice adding type hint.

The addition of /** @var T $instance */ improves code clarity by explicitly documenting the variable type, which helps with static analysis.

src/ClassList.php (1)

80-80: LGTM! Good practice adding Override attribute.

The addition of #[Override] attribute to the getIterator method improves code clarity by explicitly indicating that it overrides the method from IteratorAggregate interface.

src/TypeString.php (1)

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

The refactoring from array_map to a foreach loop with explicit type hint /** @var ReflectionNamedType $type */ improves code readability and type safety.

src/Compiler.php (1)

63-64: LGTM! Proper use of #[Override] attribute.

The #[Override] attribute correctly indicates that these methods implement interface methods, improving code clarity and maintainability.

Also applies to: 88-89

sl-src/CacheReader.php (1)

152-155: LGTM! Improved type clarity.

The explicit type annotation for $annotations improves code clarity and helps static analysis tools.

tests/BindTest.php (1)

27-149: LGTM! Excellent test method naming and documentation.

The updated test method names and docblocks significantly improve code readability and maintainability by:

  • Using descriptive names that clearly indicate what is being tested
  • Adding clear docblocks that explain the purpose of each test
  • Following a consistent naming pattern across all test methods
tests/AopCodeTest.php (1)

32-174: LGTM! Great improvements to test readability.

The changes enhance test maintainability through:

  • Clear docblocks explaining test purposes
  • More descriptive method names
  • Proper version requirements for PHP-specific tests
tests/CompilerTest.php (1)

45-454: LGTM! Excellent improvements to test quality.

The changes enhance test maintainability and type safety through:

  • Clear docblocks explaining test purposes
  • More descriptive method names
  • Proper PHPDoc annotations for arrays
  • Using PHPUnit assertions instead of assert()
vendor-bin/tools/composer.json (1)

5-9:

❓ Verification inconclusive

Verify compatibility with updated development dependencies.

Major version updates to static analysis tools may introduce breaking changes. Please ensure:

  1. The codebase is compatible with PHPStan 2.x
  2. The codebase is compatible with Psalm 6.x
  3. The new PHPMetrics version works as expected

Run the following script to check for potential compatibility issues:


🏁 Script executed:

#!/bin/bash
# Description: Verify compatibility with updated dev dependencies

# Install dependencies
composer update --working-dir=vendor-bin/tools

# Run static analysis tools
vendor/bin/phpstan analyse
vendor/bin/psalm
vendor/bin/phpmetrics --version

Length of output: 2829


Action Required: Update your PHP environment to include the SimpleXML extension before verifying the updated dev dependencies.

The current verification run failed because the Composer update in vendor-bin/tools couldn’t resolve dependencies due to the missing ext-simplexml extension (required by squizlabs/php_codesniffer and doctrine/coding-standard). As a result, none of the static analysis binaries (PHPStan, Psalm, PHPMetrics) were installed.

Please address these points:

  • Enable ext-simplexml: Ensure that the PHP CLI environment has the SimpleXML extension enabled. Alternatively, consider using Composer’s --ignore-platform-req=ext-simplexml option if that fits your context.
  • Use Composer’s dependency resolution options: Try running the update with the -W flag (e.g., composer update -W --working-dir=vendor-bin/tools) to allow for broader dependency adjustments.
  • Re-run the static analysis tools: Once the dependencies are successfully updated, verify the compatibility of:
    • PHPStan 2.x (vendor/bin/phpstan analyse)
    • Psalm 6.x (vendor/bin/psalm)
    • PHPMetrics (vendor/bin/phpmetrics --version)

@@ -4,6 +4,7 @@

namespace Ray\Aop\Matcher;

use Override;
Copy link
Contributor

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 PHP version compatibility for Override attribute.

The Override attribute requires PHP 8.3 or later. Please ensure your project's minimum PHP version requirement is compatible.

Run this script to check the PHP version requirement in composer.json:


🏁 Script executed:

#!/bin/bash
# Description: Check PHP version requirement in composer.json
if [ -f "composer.json" ]; then
    echo "PHP version requirement in composer.json:"
    cat composer.json | jq -r '.require.php'
fi

Length of output: 173


PHP Version Compatibility Issue: Update Required

The Override attribute requires PHP 8.3 or later, but the project's composer.json currently permits PHP versions from 7.2 up to the latest 8.x releases (7.2 || ^8.0). This misalignment could lead to runtime failures when the code is executed on PHP versions earlier than 8.3.

  • Action: Update the PHP version requirement in composer.json (e.g., change it to ^8.3 or >=8.3) or adjust the code to conditionally utilize the Override attribute only when running on PHP 8.3+.

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