diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 1935d097811..c020b20ee94 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -9,6 +9,7 @@ Yii Framework 2 Change Log - Enh #20247: Support for variadic console controller action methods (brandonkelly) - Bug #20256: Add support for dropping views in MSSQL server when running migrate/fresh (ambrozt) - Enh #20248: Add support for attaching behaviors in configurations with Closure (timkelty) +- Enh #20267: Fixed called class check in `Widget::end()` when widget configured using callable (rob006, jrajamaki) - Enh #20268: Minor optimisation in `\yii\helpers\BaseArrayHelper::map` (chriscpty) 2.0.51 July 18, 2024 diff --git a/framework/base/Widget.php b/framework/base/Widget.php index 450caac9c9b..b1340188449 100644 --- a/framework/base/Widget.php +++ b/framework/base/Widget.php @@ -60,6 +60,10 @@ class Widget extends Component implements ViewContextInterface */ public static $stack = []; + /** + * @var string[] used widget classes that have been resolved to their actual class name. + */ + private static $_resolvedClasses = []; /** * Initializes the object. @@ -88,6 +92,7 @@ public static function begin($config = []) /* @var $widget Widget */ $widget = Yii::createObject($config); self::$stack[] = $widget; + self::$_resolvedClasses[get_called_class()] = get_class($widget); return $widget; } @@ -104,10 +109,7 @@ public static function end() if (!empty(self::$stack)) { $widget = array_pop(self::$stack); - $calledClass = get_called_class(); - if (Yii::$container->has($calledClass) && isset(Yii::$container->getDefinitions()[$calledClass]['class'])) { - $calledClass = Yii::$container->getDefinitions()[$calledClass]['class']; - } + $calledClass = self::$_resolvedClasses[get_called_class()] ?? get_called_class(); if (get_class($widget) === $calledClass) { /* @var $widget Widget */ diff --git a/tests/framework/base/WidgetTest.php b/tests/framework/base/WidgetTest.php index 067e9480125..c67cbedd885 100644 --- a/tests/framework/base/WidgetTest.php +++ b/tests/framework/base/WidgetTest.php @@ -72,6 +72,27 @@ public function testDependencyInjection() $this->assertSame('', $output); } + public function testDependencyInjectionWithCallableConfiguration() + { + Yii::$container = new Container(); + Yii::$container->setDefinitions([ + TestWidgetB::className() => function () { + return new TestWidget(['id' => 'test']); + } + ]); + + ob_start(); + ob_implicit_flush(false); + + $widget = TestWidgetB::begin(['id' => 'test']); + $this->assertTrue($widget instanceof TestWidget); + TestWidgetB::end(); + + $output = ob_get_clean(); + + $this->assertSame('', $output); + } + /** * @depends testBeginEnd */