Skip to content

Conversation

terabytesoftw
Copy link
Member

@terabytesoftw terabytesoftw commented Jun 23, 2025

Q A
Is bugfix?
New feature? ✔️
Breaks BC?

Summary by CodeRabbit

  • New Features

    • Enhanced type inference for the ServiceLocator::get() method, providing more precise static analysis and autocompletion support in Yii2 applications.
  • Documentation

    • Updated README and documentation examples to describe and demonstrate the improved type inference for service locator usage, including new code samples and clarifications.
  • Tests

    • Added comprehensive tests to verify dynamic return type inference for service locator methods, ensuring reliability and correctness of the new feature.

… precise type inference for `get()` method.
Copy link

coderabbitai bot commented Jun 23, 2025

Walkthrough

This change introduces a dynamic return type extension for Yii's ServiceLocator::get() method, enabling precise type inference in static analysis tools like PHPStan. The update includes new documentation, configuration registration, example usage, and comprehensive tests to validate the improved type inference for service locator patterns in Yii2 applications.

Changes

Files / Paths Change Summary
CHANGELOG.md, README.md Documented the new dynamic return type extension and added usage examples for service locator type inference.
docs/examples.md Added a new example for custom service manager classes and fixed minor comment typos.
extension.neon Registered ServiceLocatorDynamicMethodReturnTypeExtension as a PHPStan dynamic method return type extension.
src/type/ServiceLocatorDynamicMethodReturnTypeExtension.php Introduced the extension class implementing precise type inference for ServiceLocator::get().
tests/data/type/ServiceLocatorDynamicMethodReturnType.php, tests/type/ServiceLocatorDynamicMethodReturnTypeExtensionTest.php Added comprehensive tests to verify dynamic return type inference for service locator usage.

Sequence Diagram(s)

sequenceDiagram
    participant StaticAnalyzer as PHPStan
    participant Extension as ServiceLocatorDynamicMethodReturnTypeExtension
    participant ServiceLocator as ServiceLocator
    participant ServiceMap as ServiceMap
    participant Reflection as ReflectionProvider

    StaticAnalyzer->>Extension: Analyze ServiceLocator::get($id)
    Extension->>ServiceMap: Resolve $id to class/service
    alt Known component/service
        ServiceMap-->>Extension: Return class name
        Extension->>Reflection: Verify class exists
        Reflection-->>Extension: Class exists
        Extension-->>StaticAnalyzer: Return ObjectType(class)
    else Unknown or dynamic $id
        Extension-->>StaticAnalyzer: Return MixedType
    end
Loading

Possibly related PRs

  • yii2-extensions/phpstan#39: Implements a similar dynamic return type extension for Container::get(), using analogous logic for a different service retrieval class.

Suggested labels

enhancement

Poem

In the warren of code, where services hide,
The rabbit hops in, with PHPStan as guide.
Now get() knows what it returns,
From class names or IDs, the answer it learns.
With type hints so clear,
Static bugs disappear—
Yii2’s locator hops forward this year! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Jun 23, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (cc5204b) to head (3591bf8).

Additional details and impacted files
@@             Coverage Diff             @@
##                main       #56   +/-   ##
===========================================
  Coverage     100.00%   100.00%           
  Complexity        71        71           
===========================================
  Files              2         2           
  Lines            129       129           
===========================================
  Hits             129       129           

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

🧹 Nitpick comments (1)
src/type/ServiceLocatorDynamicMethodReturnTypeExtension.php (1)

97-97: Consider using instanceof for more robust type checking.

The current type check $methodCall->args[0]::class !== Arg::class is unusual and only checks for the exact class. Using instanceof would be more conventional and handle subclasses properly:

-if (isset($methodCall->args[0]) === false || $methodCall->args[0]::class !== Arg::class) {
+if (isset($methodCall->args[0]) === false || !$methodCall->args[0] instanceof Arg) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cc5204b and 3591bf8.

📒 Files selected for processing (7)
  • CHANGELOG.md (1 hunks)
  • README.md (2 hunks)
  • docs/examples.md (5 hunks)
  • extension.neon (1 hunks)
  • src/type/ServiceLocatorDynamicMethodReturnTypeExtension.php (1 hunks)
  • tests/data/type/ServiceLocatorDynamicMethodReturnType.php (1 hunks)
  • tests/type/ServiceLocatorDynamicMethodReturnTypeExtensionTest.php (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: phpunit / PHP 8.1-windows-latest
  • GitHub Check: phpunit / PHP 8.1-ubuntu-latest
  • GitHub Check: phpunit-compatibility / PHP 8.1-windows-latest
  • GitHub Check: phpunit-compatibility / PHP 8.4-ubuntu-latest
  • GitHub Check: composer-require-checker / PHP 8.4-ubuntu-latest
🔇 Additional comments (15)
CHANGELOG.md (1)

26-26: LGTM: Changelog entry is properly formatted.

The enhancement entry follows the established format and accurately describes the new ServiceLocator dynamic return type extension feature.

extension.neon (1)

50-52: LGTM: Service registration is properly configured.

The ServiceLocatorDynamicMethodReturnTypeExtension is correctly registered with the appropriate PHPStan tag and follows the established pattern of other dynamic return type extensions.

docs/examples.md (2)

89-89: LGTM: Minor grammar correction.

The comment correction from "knows this returns" to "knows this return" improves grammatical consistency.


457-499: LGTM: Comprehensive service locator examples.

The new "Service locator in custom classes" section provides excellent practical examples demonstrating:

  • Custom ServiceLocator extension
  • Type-safe service resolution by ID and class name
  • Proper error handling with logging
  • Multiple service resolution patterns

The examples effectively showcase the enhanced type inference capabilities.

tests/type/ServiceLocatorDynamicMethodReturnTypeExtensionTest.php (1)

31-55: LGTM: Well-structured PHPStan test class.

The test class properly follows PHPStan's testing patterns:

  • Correct inheritance from TypeInferenceTestCase
  • Proper use of data provider for fixture-based testing
  • Additional config file specification for extension testing
  • Comprehensive documentation explaining the test purpose and features

The implementation ensures robust testing of the ServiceLocator dynamic return type extension.

src/type/ServiceLocatorDynamicMethodReturnTypeExtension.php (1)

38-148: LGTM: Solid implementation of dynamic return type extension.

The ServiceLocatorDynamicMethodReturnTypeExtension is well-implemented with:

Strengths:

  • Proper implementation of DynamicMethodReturnTypeExtension interface
  • Sound type resolution logic with appropriate fallback chain
  • Comprehensive error handling and edge case management
  • Excellent documentation with detailed PHPDoc comments
  • Proper dependency injection pattern
  • Focuses on the correct method (get) and class (ServiceLocator)

Type Resolution Logic:

  1. Component class resolution via ServiceMap
  2. Service class resolution via ServiceMap
  3. Direct class name verification via ReflectionProvider
  4. Fallback to MixedType for unknown/dynamic cases

This approach provides precise type inference while maintaining compatibility with PHPStan's analysis framework.

README.md (2)

60-65: Well-documented feature with clear resolution priority.

The Service Locator Component Resolution section effectively explains the new dynamic return type extension with clear priority ordering and comprehensive coverage of supported scenarios.


169-185: Comprehensive examples demonstrating the new functionality.

The service locator examples clearly illustrate the enhanced type inference capabilities, showing both class-based and string-based component resolution with appropriate type annotations.

tests/data/type/ServiceLocatorDynamicMethodReturnType.php (7)

1-34: Well-structured test file with comprehensive documentation.

The file header, imports, and class documentation clearly explain the purpose and scope of the ServiceLocator type inference tests. The PHPDoc is particularly thorough in explaining the test scenarios and key features.


40-45: Correct test for class name constant resolution.

This test validates that ServiceLocator::get() with a class name constant returns the expected type. The assertion correctly uses the fully qualified class name string.


50-57: Effective test for string variable class name resolution.

This test demonstrates that the extension can infer types even when the class name is passed as a string variable, which is important for real-world usage patterns.


62-67: Proper fallback behavior validation.

This test correctly validates that unknown component identifiers fall back to mixed type, which aligns with the documented behavior in the README.


72-80: Comprehensive testing of built-in Yii2 components.

The test covers multiple built-in Yii2 classes to ensure the extension works correctly with framework components.


85-103: Thorough testing of component ID resolution and parameters.

These tests validate both component ID string resolution and the optional $throwException parameter, ensuring the extension handles all method signatures correctly.


108-125: Proper testing of ServiceLocator subclasses.

The tests correctly validate that the extension works with Application and Module classes, which inherit from ServiceLocator, ensuring comprehensive framework integration.

@terabytesoftw terabytesoftw requested a review from Copilot June 23, 2025 11:25
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR introduces the ServiceLocatorDynamicMethodReturnTypeExtension to improve type inference for ServiceLocator::get() calls in Yii2 applications. It adds dynamic return type extension logic, updates tests and fixtures, and refines documentation and examples accordingly.

  • Implements dynamic type resolution for service locator calls.
  • Adds comprehensive tests and fixtures for the new feature.
  • Updates documentation and changelog to reflect the precise type inference support.

Reviewed Changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/type/ServiceLocatorDynamicMethodReturnTypeExtensionTest.php Adds test coverage for the new dynamic return type extension.
tests/data/type/ServiceLocatorDynamicMethodReturnType.php Introduces type assertion tests for various component resolution scenarios.
src/type/ServiceLocatorDynamicMethodReturnTypeExtension.php Implements dynamic return type logic based on ServiceMap and ReflectionProvider.
extension.neon Registers the new extension with PHPStan.
docs/examples.md Updates examples to reflect the improved type inference behavior.
README.md Documents the new capabilities for ServiceLocator component resolution.
CHANGELOG.md Records the new feature in the changelog.

@terabytesoftw terabytesoftw merged commit 7c43584 into main Jun 23, 2025
45 checks passed
@terabytesoftw terabytesoftw deleted the feat-mini-7 branch June 23, 2025 11:27
@terabytesoftw terabytesoftw added the enhancement New feature or request label Jul 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant