Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
- Bug #53: Update documentation for consistency and clarity; change section titles and add strict types declaration (@terabytesoftw)
- Bug #54: Update `PHPStan` `tmpDir` config; move `runtime` directory to `root`; update docs (@terabytesoftw)
- Bug #55: Remove `OS` and `PHP` version specifications from workflow files for simplification (@terabytesoftw)
- Enh #56: Add `ServiceLocatorDynamicMethodReturnTypeExtension` to provide precise type inference for `get()` method (@terabytesoftw)

## 0.2.3 June 09, 2025

Expand Down
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ inference, dynamic method resolution, and comprehensive property reflection.
- Stub files for different application types (web, console, base).
- Support for Yii2 constants (`YII_DEBUG`, `YII_ENV_*`).

✅ **Service Locator Component Resolution**
- Automatic fallback to mixed type for unknown component identifiers.
- Dynamic return type inference for `ServiceLocator::get()` calls.
- Priority-based resolution: ServiceMap components > ServiceMap services > Real classes > Mixed type.
- Support for all Service Locator subclasses (Application, Module, custom classes).
- Type inference with string variables and class name constants.

## Quick start

### Installation
Expand Down Expand Up @@ -159,7 +166,22 @@ $container = new Container();

// ✅ Type-safe service resolution
$service = $container->get(MyService::class); // MyService
$logger = $container->get('logger'); // LoggerInterface (if configured)
$logger = $container->get('logger'); // LoggerInterface (if configured) or mixed
```

#### Service locator

```php
$serviceLocator = new ServiceLocator();

// ✅ Get component with type inference with class
$mailer = $serviceLocator->get(Mailer::class); // MailerInterface

// ✅ Get component with string identifier and without configuration in ServiceMap
$mailer = $serviceLocator->get('mailer'); // MailerInterface (if configured) or mixed

// ✅ User component with proper type inference in Action or Controller
$user = $this->controller->module->get('user'); // UserInterface
```

## Documentation
Expand Down
54 changes: 49 additions & 5 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ class PostRepository

public function getLatestPost(): Post|null
{
// ✅ PHPStan knows this returns Post|null
// ✅ PHPStan knows this return Post|null
return Post::find()
->where(['status' => 'published'])
->orderBy('created_at DESC')
Expand Down Expand Up @@ -114,13 +114,13 @@ class UserModel extends \yii\db\ActiveRecord
{
public function getPosts(): \yii\db\ActiveQuery
{
// ✅ PHPStan knows this returns ActiveQuery<Post>
// ✅ PHPStan knows this return ActiveQuery<Post>
return $this->hasMany(Post::class, ['author_id' => 'id']);
}

public function getProfile(): \yii\db\ActiveQuery
{
// ✅ PHPStan knows this returns ActiveQuery<UserProfile>
// ✅ PHPStan knows this return ActiveQuery<UserProfile>
return $this->hasOne(UserProfile::class, ['user_id' => 'id']);
}
}
Expand Down Expand Up @@ -194,7 +194,7 @@ class Post extends \yii\db\ActiveRecord
{
public static function find(): PostQuery
{
// ✅ PHPStan knows this returns PostQuery<Post>
// ✅ PHPStan knows this return PostQuery<Post>
return new PostQuery(get_called_class());
}
}
Expand Down Expand Up @@ -429,7 +429,7 @@ class ServiceManager

public function getPaymentService(): PaymentService
{
// ✅ PHPStan knows this returns PaymentService
// ✅ PHPStan knows this return PaymentService
return $this->container->get(PaymentService::class);
}

Expand All @@ -454,6 +454,50 @@ class ServiceManager
}
```

### Service locator in custom classes

```php
<?php

declare(strict_types=1);

use yii\di\ServiceLocator;
use app\services\{EmailService, LoggerService, CacheService};

class CustomServiceManager extends ServiceLocator
{
public function sendNotification(string $message): bool
{
// ✅ PHPStan knows these are the correct service types
$email = $this->get('emailService'); // EmailService
$logger = $this->get('loggerService'); // LoggerService
$cache = $this->get('cacheService'); // CacheService

try {
$result = $email->send($message);
$logger->info('Notification sent successfully');
$cache->delete('pending_notifications');

return $result;
} catch (\Exception $e) {
$logger->error('Failed to send notification: ' . $e->getMessage());
return false;
}
}

public function getServicesByType(): array
{
// ✅ Different ways to resolve services
return [
'email_by_id' => $this->get('emailService'), // EmailService
'email_by_class' => $this->get(EmailService::class), // EmailService
'logger_by_id' => $this->get('loggerService'), // LoggerService
'logger_by_class' => $this->get(LoggerService::class), // LoggerService
];
}
}
```

### Service configuration examples

```php
Expand Down
3 changes: 3 additions & 0 deletions extension.neon
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ services:
-
class: yii2\extensions\phpstan\type\HeaderCollectionDynamicMethodReturnTypeExtension
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]
-
class: yii2\extensions\phpstan\type\ServiceLocatorDynamicMethodReturnTypeExtension
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]
-
class: yii2\extensions\phpstan\StubFilesExtension
tags:
Expand Down
148 changes: 148 additions & 0 deletions src/type/ServiceLocatorDynamicMethodReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
<?php

declare(strict_types=1);

namespace yii2\extensions\phpstan\type;

use PhpParser\Node\Arg;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\{MethodReflection, ParametersAcceptorSelector, ReflectionProvider};
use PHPStan\Type\{DynamicMethodReturnTypeExtension, MixedType, ObjectType, Type};
use yii\di\ServiceLocator;
use yii2\extensions\phpstan\ServiceMap;

/**
* Provides dynamic return type extension for Yii Service Locator component resolution in PHPStan analysis.
*
* Integrates the Yii Service Locator service {@see ServiceLocator} with PHPStan dynamic method return type extension
* system, enabling precise type inference for {@see ServiceLocator::get()} calls based on component ID and the
* {@see ServiceMap}.
*
* This extension analyzes the first argument of {@see ServiceLocator::get()} to determine the most accurate return
* type, returning an {@see ObjectType} for known component classes or a {@see MixedType} for unknown or dynamic ID.
*
* Key features:
* - Accurate return type inference for {@see ServiceLocator::get()} based on component ID string.
* - Compatible with PHPStan strict static analysis and autocompletion.
* - Falls back to method signature return type for unsupported or invalid calls.
* - Supports Yii modules, applications, and any class extending {@see ServiceLocator}.
* - Uses {@see ServiceMap} to resolve component class names.
*
* @see DynamicMethodReturnTypeExtension for PHPStan dynamic return type extension contract.
* @see ServiceMap for service and component map for Yii Application static analysis.
*
* @copyright Copyright (C) 2023 Terabytesoftw.
* @license https://opensource.org/license/bsd-3-clause BSD 3-Clause License.
*/
final class ServiceLocatorDynamicMethodReturnTypeExtension implements DynamicMethodReturnTypeExtension
{
/**
* Creates a new instance of the {@see ServiceLocatorDynamicMethodReturnTypeExtension} class.
*
* @param ReflectionProvider $reflectionProvider Reflection provider for class and property lookups.
* @param ServiceMap $serviceMap Service and component map for Yii Application static analysis.
*/
public function __construct(
private readonly ReflectionProvider $reflectionProvider,
private readonly ServiceMap $serviceMap,
) {}

/**
* Returns the class name for which this dynamic return type extension applies.
*
* Specifies the fully qualified class name of the Yii ServiceLocator {@see ServiceLocator} that this extension
* target for dynamic return type inference in PHPStan analysis.
*
* This method enables PHPStan to associate the extension with the {@see ServiceLocator} class and all its
* subclasses (like Module and Application), ensuring that dynamic return type logic is applied to component
* resolution calls.
*
* @return string Fully qualified class name of the supported ServiceLocator class.
*
* @phpstan-return class-string
*/
public function getClass(): string
{
return ServiceLocator::class;
}

/**
* Infers the return type for a {@see ServiceLocator::get()} method call based on the provided component ID
* argument.
*
* Determines the most accurate return type for component resolution by analyzing the first argument of the
* {@see ServiceLocator::get()} call.
*
* - If the argument is a constant string and matches a known component in the {@see ServiceMap}, returns an
* {@see ObjectType} for the resolved class.
* - If the argument is a class name known to the {@see ReflectionProvider}, returns an {@see ObjectType} for that
* class.
* - Otherwise, returns a {@see MixedType} to indicate an unknown or dynamic component type.
*
* Falls back to the default method signature return type for unsupported or invalid calls, ensuring compatibility
* with PHPStan static analysis and IDE autocompletion.
*
* @param MethodReflection $methodReflection Reflection instance for the method being analyzed.
* @param MethodCall $methodCall AST node for the method call expression.
* @param Scope $scope PHPStan analysis scope for type resolution.
*
* @return Type Inferred return type for the component resolution call.
*/
public function getTypeFromMethodCall(
MethodReflection $methodReflection,
MethodCall $methodCall,
Scope $scope,
): Type {
if (isset($methodCall->args[0]) === false || $methodCall->args[0]::class !== Arg::class) {
return ParametersAcceptorSelector::selectFromArgs(
$scope,
$methodCall->getArgs(),
$methodReflection->getVariants(),
)->getReturnType();
}

$argType = $scope->getType($methodCall->args[0]->value);
$constantStrings = $argType->getConstantStrings();

if (count($constantStrings) === 1) {
$value = $constantStrings[0]->getValue();

$componentClass = $this->serviceMap->getComponentClassById($value);

if ($componentClass !== null) {
return new ObjectType($componentClass);
}

$serviceClass = $this->serviceMap->getServiceById($value);

if ($serviceClass !== null) {
return new ObjectType($serviceClass);
}

if ($this->reflectionProvider->hasClass($value)) {
return new ObjectType($value);
}
}

return new MixedType();
}

/**
* Determines whether the specified method is supported for dynamic return type inference.
*
* Checks if the method name is {@see ServiceLocator::get}, which is the only method supported by this extension for
* dynamic return type analysis.
*
* This enables PHPStan to apply custom type inference logic exclusively to component resolution calls on the Yii
* Service Locator {@see ServiceLocator} and its subclasses (Module, Application).
*
* @param MethodReflection $methodReflection Reflection instance for the method being analyzed.
*
* @return bool `true` if the method is {@see ServiceLocator::get}; `false` otherwise.
*/
public function isMethodSupported(MethodReflection $methodReflection): bool
{
return $methodReflection->getName() === 'get';
}
}
Loading