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

Fix #20332: Added support for the '__class' key in \yii\di\Instance:eunsure(['__class' => ...]) #20332

Merged
merged 2 commits into from
Feb 27, 2025
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 framework/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Yii Framework 2 Change Log
- Chg #20276: Removed autogenerated migration phpdoc (userator)
- New #20185: Add `BackedEnum` support to `AttributeTypecastBehavior` (briedis)
- New #20279: Add to the `\yii\web\Request` CSRF validation by custom HTTP header (olegbaturin)
- New #20332: Added support for the '__class' key in `\yii\di\Instance:eunsure(['__class' => ...])` (LAV45)


2.0.51 July 18, 2024
Expand Down
11 changes: 9 additions & 2 deletions framework/di/Instance.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,18 @@
public static function ensure($reference, $type = null, $container = null)
{
if (is_array($reference)) {
$class = isset($reference['class']) ? $reference['class'] : $type;
if (!$container instanceof Container) {
$container = Yii::$container;
}
unset($reference['class']);
if (isset($reference['__class'])) {
$class = $reference['__class'];
unset($reference['__class'], $type['class']);
} elseif (isset($reference['class'])) {
$class = $reference['class'];
unset($reference['class']);
} else {
$class = $type;

Check warning on line 131 in framework/di/Instance.php

View check run for this annotation

Codecov / codecov/patch

framework/di/Instance.php#L131

Added line #L131 was not covered by tests
}
$component = $container->get($class, [], $reference);
if ($type === null || $component instanceof $type) {
return $component;
Expand Down
1 change: 1 addition & 0 deletions tests/framework/di/InstanceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ public function testEnsure_MinimalSettings()
$this->assertInstanceOf(Connection::className(), Instance::ensure('db'));
$this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection()));
$this->assertInstanceOf(Connection::className(), Instance::ensure(['class' => 'yii\db\Connection', 'dsn' => 'test']));
$this->assertInstanceOf(Connection::className(), Instance::ensure(['__class' => 'yii\db\Connection', 'dsn' => 'test']));
Yii::$container = new Container();
}

Expand Down
Loading