diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 80a0547e494..294810f9fc7 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -8,6 +8,7 @@ Yii Framework 2 Change Log - Bug #20231: Fix regression introduced in #20167 in `yii\validators\FileValidator` (bizley) - 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) 2.0.51 July 18, 2024 -------------------- diff --git a/framework/base/Component.php b/framework/base/Component.php index 7838f4b1da2..937de6b44e7 100644 --- a/framework/base/Component.php +++ b/framework/base/Component.php @@ -190,6 +190,8 @@ public function __set($name, $value) $name = trim(substr($name, 3)); if ($value instanceof Behavior) { $this->attachBehavior($name, $value); + } elseif ($value instanceof \Closure) { + $this->attachBehavior($name, call_user_func($value)); } elseif (isset($value['__class']) && is_subclass_of($value['__class'], Behavior::class)) { $this->attachBehavior($name, Yii::createObject($value)); } elseif (!isset($value['__class']) && isset($value['class']) && is_subclass_of($value['class'], Behavior::class)) { diff --git a/tests/framework/base/ComponentTest.php b/tests/framework/base/ComponentTest.php index d16671a5fa1..8f9f3ba5408 100644 --- a/tests/framework/base/ComponentTest.php +++ b/tests/framework/base/ComponentTest.php @@ -366,6 +366,12 @@ public function testAttachBehavior() } catch (InvalidConfigException $e) { $this->assertSame('Class is not of type yii\base\Behavior or its subclasses', $e->getMessage()); } + + $component = new NewComponent(); + $component->{'as f'} = function () { + return new NewBehavior(); + }; + $this->assertNotNull($component->getBehavior('f')); } public function testAttachBehaviors()