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

Use Ray.Aop's new binding injector _setBindings #297

Closed
wants to merge 10 commits into from

Conversation

koriym
Copy link
Member

@koriym koriym commented Feb 22, 2025

  • Change from the method of setting directly to the $bindings property to the method of using the new method
  • Adjustments to pass the CI

Summary by Sourcery

This pull request updates the dependency injection mechanism to use Ray.Aop's new binding injector, enhancing the framework's capabilities and preparing it for future development. It also includes updates to the build and CI configurations, as well as improvements to the test suite.

Enhancements:

  • Replaced direct property setting with the _setBindings method in Ray\Di\NewInstance to inject dependencies, leveraging the new binding injector in Ray.Aop.
  • Improved code quality by adding assertions to ensure type safety and prevent potential errors.

Build:

  • Updated the ray/aop dependency to the ^2.x-dev version to utilize the latest features and improvements.

CI:

  • Added a baseline for Psalm to track and manage static analysis errors over time.

Tests:

  • Improved test robustness by normalizing line endings in string comparisons to avoid failures due to different operating system conventions.

Summary by CodeRabbit

  • New Features
    • Introduced a streamlined mechanism for enabling aspect-oriented programming enhancements, providing a clearer and more maintainable integration approach.
  • Chores
    • Updated dependency configurations and analysis scripts to improve overall quality and error tracking.
    • Added baseline support for enhanced static analysis and error management.
  • Tests
    • Improved test stability by standardizing output comparisons and refining analysis annotations.

The "baseline" script generates static analysis baselines for PHPStan and Psalm. This simplifies managing analysis results and helps suppress existing issues for future incremental improvements.
Introduced baseline files for PHPStan and Psalm to suppress known issues temporarily, improving focus on new errors. Added references to these baselines in the respective configuration files to aid static analysis setup.
Moved Aspect-Oriented Programming (AOP) binding logic to a new `enableAop` method for better modularity and clarity. Replaced direct assertions with a safer method call (`__setBindings`) to streamline the binding process and improve maintainability.
Switched the Ray/AOP dependency from a stable version to the ^2.x-dev branch. This allows for using the latest development changes while maintaining compatibility with the project.
Added stricter type assertion in `AnnotatedClassMethods` with `assert` to ensure constructor type safety. Removed unnecessary suppression comments and improved type annotations for better code reliability and maintainability.
Upgraded multiple packages to ensure compatibility and receive the latest bug fixes and improvements. Adjusted metadata such as branch aliases and autoload paths where necessary. This helps maintain system stability and prepares for future development.
Disabled the `--show-info` output in the `sa` script for psalm to reduce unnecessary verbosity. This ensures the analysis output remains focused on essential issues.
Added a normalization function to standardize line endings to '\n' in string assertions for consistent behavior across environments. Updated the test to apply this normalization to both expected and actual strings.
Copy link

sourcery-ai bot commented Feb 22, 2025

Reviewer's Guide by Sourcery

This pull request migrates the AOP binding injection to use the _setBindings method provided by Ray.Aop, updates the ray/aop dependency to the latest development version, and includes adjustments for CI and cross-platform compatibility. It also adds baseline files for static analysis tools.

Sequence diagram for AOP binding injection using _setBindings

sequenceDiagram
  participant NewInstance
  participant AspectBind
  participant WeavedInterface
  participant Container

  NewInstance->>NewInstance: enableAop(instance, container)
  alt bind instanceof AspectBind
    NewInstance->>AspectBind: inject(container)
    AspectBind-->>NewInstance: bindings
    NewInstance->>WeavedInterface: _setBindings(bindings)  // Ray.Aop ^2.18
  end
Loading

File-Level Changes

Change Details Files
Replaced direct property setting with the _setBindings method for injecting AOP bindings.
  • Modified NewInstance::postNewInstance() to call enableAop().
  • Created NewInstance::enableAop() to handle AOP binding injection using _setBindings().
  • Removed direct assignment to $instance->bindings.
  • Added assertion to ensure the instance implements WeavedInterface before calling _setBindings().
src/di/NewInstance.php
Updated ray/aop dependency to the latest development version and adjusted code to align with changes in the AOP package.
  • Updated composer.json to require ray/aop: ^2.x-dev.
  • Modified AspectBind::inject() to specify a non-empty string for the array key.
  • Added assertions to AnnotatedClassMethods::getConstructorName() to ensure $constructor is a ReflectionMethod.
  • Removed @phpstan-ignore-line from BindValidator::to().
  • Removed @phpstan-ignore-line from AnnotatedClassTest::testInvoke().
composer.json
src/di/AspectBind.php
src/di/AnnotatedClassMethods.php
src/di/BindValidator.php
tests/di/AnnotatedClassTest.php
Updated test case to normalize line endings for cross-platform compatibility.
  • Added a normalize function to replace different line endings with `
.</li><li>Used the normalizefunction to compare strings inModuleTest::testToString()`. tests/di/ModuleTest.php
Added baseline files for static analysis tools.
  • Added psalm-baseline.xml.
  • Added phpstan-baseline.neon.
psalm-baseline.xml
phpstan-baseline.neon

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

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

  • Consider adding a more specific assertion message in NewInstance::enableAop to clarify the expected interface.
  • The change to ray/aop to ^2.x-dev should be reverted.
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.

Copy link

coderabbitai bot commented Feb 22, 2025

Walkthrough

The changes update dependency versions and modify static analysis configurations. They adjust script commands in the package configuration, add new baseline configuration files for PHPStan and Psalm, and update annotations for improved type safety. The DI-related code is refactored by adding assertions and a new method for enhancing AOP behavior, while test cases are updated to handle line normalization and PHPStan ignore comments.

Changes

File(s) Change Summary
composer.json Updated dependency "ray/aop" from "^2.16" to "^2.x-dev", modified the "sa" script to change Psalm's --show-info flag to false, and added a new "baseline" script for generating PHPStan and Psalm baselines.
phpstan-baseline.neon, psalm-baseline.xml Added new baseline configuration files: phpstan-baseline.neon specifies PHPStan ignore rules, and psalm-baseline.xml documents reported issues as a baseline for Psalm analysis.
psalm.xml Introduced the attribute errorBaseline with the value psalm-baseline.xml to reference the new baseline file for error reporting.
src/di/AnnotatedClassMethods.php Added an assertion to ensure that the $constructor variable is an instance of ReflectionMethod within the getConstructorName method.
src/di/AspectBind.php, src/di/BindValidator.php Updated PHPDoc in AspectBind.php to change the return type to array<non-empty-string, list<MethodInterceptor>> and removed a PHPStan ignore comment in BindValidator.php from the to method.
src/di/NewInstance.php Introduced a new public method enableAop to encapsulate AOP enabling logic.
tests/di/AnnotatedClassTest.php, tests/di/ModuleTest.php Added a PHPStan ignore-line comment to a test case in AnnotatedClassTest.php and incorporated a normalization function for line endings in ModuleTest.php to ensure consistent string comparisons.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant NewInstance
    participant AspectBind
    participant WeavedInterface

    Client->>NewInstance: Request new instance creation
    NewInstance->>NewInstance: Call enableAop(instance, container)
    alt Bind is instance of AspectBind
        NewInstance->>AspectBind: Call inject() to retrieve bindings
        AspectBind-->>NewInstance: Return bindings
        NewInstance->>WeavedInterface: Set bindings via _setBindings()
    else Bind is not an instance of AspectBind
        NewInstance-->>Client: Return instance without AOP modifications
    end
Loading

Poem

Oh, the code hops light and fast,
AOP enabled, improvements vast.
Baselines set to catch the flaws,
Type checks hop with no pause.
I'm a rabbit, dancing in the code glen,
Celebrating changes again and again! 🐇✨

✨ 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

@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

🧹 Nitpick comments (1)
tests/di/AnnotatedClassTest.php (1)

24-24: Evaluate the Necessity of the PHPStan Ignore Comment
Static analysis indicates that no PHPStan error is reported on this line. Please confirm if the // @phpstan-ignore-line directive is still needed. If it was added to bypass a past false positive that is no longer applicable, consider removing it to keep the code clean and avoid masking potential issues in the future.

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

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

(ignore.unmatchedLine)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f033242 and 4ad4d5f.

⛔ Files ignored due to path filters (1)
  • vendor-bin/tools/composer.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • composer.json (2 hunks)
  • phpstan-baseline.neon (1 hunks)
  • psalm-baseline.xml (1 hunks)
  • psalm.xml (1 hunks)
  • src/di/AnnotatedClassMethods.php (2 hunks)
  • src/di/AspectBind.php (1 hunks)
  • src/di/BindValidator.php (1 hunks)
  • src/di/NewInstance.php (2 hunks)
  • tests/di/AnnotatedClassTest.php (1 hunks)
  • tests/di/ModuleTest.php (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • phpstan-baseline.neon
🧰 Additional context used
🪛 PHPStan (2.0.3)
src/di/BindValidator.php

45-45: Method Ray\Di\BindValidator::to() should return Ray\Aop\ReflectionClass but returns Ray\Aop\ReflectionClass.

(return.type)

tests/di/AnnotatedClassTest.php

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

(ignore.unmatchedLine)

🔇 Additional comments (9)
src/di/AspectBind.php (1)

25-25: LGTM! Enhanced type safety for method names.

The change from string to non-empty-string in the return type annotation is a good improvement as it better reflects that method names cannot be empty strings, helping catch potential issues during static analysis.

tests/di/ModuleTest.php (1)

10-11: LGTM! Improved test reliability with line ending normalization.

The addition of the $normalize function makes the test more robust by handling different OS line endings (CRLF, CR, LF) consistently.

Also applies to: 55-57

src/di/AnnotatedClassMethods.php (1)

12-12: LGTM! Enhanced type safety with runtime assertion.

The addition of the assertion helps ensure type safety by verifying that $constructor is a ReflectionMethod before use, making the code more robust and helping static analysis tools verify type correctness.

Also applies to: 43-43

src/di/NewInstance.php (3)

8-8: LGTM! Added import for type safety.

The addition of WeavedInterface import enhances type safety for AOP functionality.


98-98: LGTM! Improved code organization.

Extracting AOP logic into a dedicated method improves code organization and maintainability.


106-115: LGTM! Well-structured AOP enablement.

The new enableAop method:

  • Properly checks for AspectBind instance
  • Ensures type safety with WeavedInterface assertion
  • Uses Ray.Aop's new _setBindings method as intended
psalm.xml (1)

7-7: LGTM! Added error baseline configuration.

The addition of errorBaseline improves static analysis management by tracking known issues.

psalm-baseline.xml (1)

28-31:

❓ Verification inconclusive

Verify the InvalidArgument issue in NewInstance.

The baseline indicates a potential type mismatch in $this->bind->inject($container). Please verify that the type signatures are correct with the new _setBindings implementation.


🏁 Script executed:

#!/bin/bash
# Check the return type of inject() method and parameter type of _setBindings
ast-grep --pattern 'class AspectBind {
  $$$
  inject($$$) {
    $$$
  }
}'

ast-grep --pattern 'interface WeavedInterface {
  $$$
  _setBindings($$$) {
    $$$
  }
}'

Length of output: 170


Attention: Verify Type Signatures for InvalidArgument Issue in NewInstance

The psalm baseline still flags a potential type mismatch in the call to $this->bind->inject($container) in src/di/NewInstance.php. Our initial automated search for the definitions of the inject() method in the AspectBind class and the _setBindings() method in the WeavedInterface did not return any results. This lack of output suggests that additional manual verification is required.

Please verify the following manually:

  • Confirm that the inject() method in the AspectBind class is declared with the correct parameter and return types.
  • Ensure that the _setBindings() method in the WeavedInterface is implemented with a signature that is consistent with what inject() expects when invoked in NewInstance.php.

If you find any discrepancies between these signatures—especially in light of the new _setBindings implementation—please update them to resolve the InvalidArgument issue.

composer.json (1)

50-50: LGTM! Improved static analysis configuration.

The changes enhance the static analysis setup:

  • Reduced noise by disabling info messages
  • Added baseline generation commands

Also applies to: 54-54

@@ -42,7 +42,7 @@ public function to(string $interface, string $class): ReflectionClass
throw new InvalidType("[{$class}] is no implemented [{$interface}] interface");
}

return new ReflectionClass($class); // @phpstan-ignore-line
return new ReflectionClass($class);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix type safety issue in return type.

The method promises to return ReflectionClass<T> but returns ReflectionClass<object>, which could lead to type safety issues.

Apply this diff to fix the type safety issue:

-        return new ReflectionClass($class);
+        /** @var ReflectionClass<T> */
+        $reflectionClass = new ReflectionClass($class);
+        return $reflectionClass;
📝 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
return new ReflectionClass($class);
/** @var ReflectionClass<T> */
$reflectionClass = new ReflectionClass($class);
return $reflectionClass;
🧰 Tools
🪛 PHPStan (2.0.3)

45-45: Method Ray\Di\BindValidator::to() should return Ray\Aop\ReflectionClass but returns Ray\Aop\ReflectionClass.

(return.type)

@@ -14,7 +14,7 @@
"koriym/attributes": "^1.0.4",
"koriym/null-object": "^1.0",
"koriym/param-reader": "^1.0",
"ray/aop": "^2.16",
"ray/aop": "^2.x-dev",
Copy link

@coderabbitai coderabbitai bot Feb 22, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify the stability implications of using dev version.

Using ^2.x-dev for ray/aop could introduce instability. Consider using a stable version that supports _setBindings.


🌐 Web query:

What is the latest stable version of ray/aop that supports _setBindings method?

💡 Result:

The latest stable version of Ray.Aop that supports the _setBindings method is version 2.16 "Tanabata", as indicated by its release notes[10]. However, this version introduces significant API simplifications and shifts toward using bind() instead of _setBindings for aspect configuration[1][10].

Key points:

  • Version 2.16 explicitly mentions API changes aimed at simplifying usage[10].
  • Earlier versions (like 2.10.x) still support _setBindings, as seen in Laravel integration examples requiring ray/aop ^2.10.1[4].
  • The newer bind() method (demonstrated in examples[1]) replaces _setBindings in modern implementations:
    $aspect->bind((new Matcher())->any(), ..., [new Interceptor()]);

For projects requiring _setBindings, use versions ≤2.15, but consider migrating to bind() for future compatibility[10]. Always verify method availability in specific releases via official documentation[1][10].

Citations:


Stable Dependency Recommendation: Update ray/aop Version

  • The use of "ray/aop": "^2.x-dev" poses a potential risk due to instability from a dev release.
  • If your project depends on the legacy _setBindings method, note that while version 2.16 "Tanabata" is the latest stable release, it shifts to using bind(), which may introduce breaking API changes.
  • To preserve compatibility with _setBindings, consider pinning the dependency to a stable version prior to 2.16 (e.g., ^2.15.0 or an earlier 2.x release).
  • Alternatively, if you prefer to upgrade, update your codebase to switch from _setBindings to the new bind() method as per the API changes in 2.16.

Copy link
Member Author

Choose a reason for hiding this comment

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

@coderabbitai The next version still not released.

Copy link

Choose a reason for hiding this comment

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

@koriym Understood, thank you for the clarification about the unreleased version.


✏️ Learnings added
Learnt from: koriym
PR: ray-di/Ray.Di#297
File: composer.json:17-17
Timestamp: 2025-02-22T08:34:22.538Z
Learning: The use of "ray/aop": "^2.x-dev" in composer.json is intentional as it depends on features from the upcoming version that hasn't been released yet.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@koriym
Copy link
Member Author

koriym commented Feb 23, 2025

Move to #298

@koriym koriym closed this Feb 23, 2025
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