From cc05f92181f74627054ffe89b9fd7c9b78cc8320 Mon Sep 17 00:00:00 2001 From: Tim Kelty Date: Wed, 21 Aug 2024 23:35:57 -0400 Subject: [PATCH] Attach behavior via "as foo" with Closure --- framework/base/Component.php | 2 ++ tests/framework/base/ComponentTest.php | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/framework/base/Component.php b/framework/base/Component.php index 7cee3b0720d..9cab8373ae3 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)) || (isset($value['__class']) && is_subclass_of($value['__class'], Behavior::class))) { $this->attachBehavior($name, Yii::createObject($value)); } elseif (is_string($value) && is_subclass_of($value, Behavior::class, true)) { diff --git a/tests/framework/base/ComponentTest.php b/tests/framework/base/ComponentTest.php index dca3c37bd91..725a7ee7878 100644 --- a/tests/framework/base/ComponentTest.php +++ b/tests/framework/base/ComponentTest.php @@ -344,6 +344,11 @@ public function testAttachBehavior() $component->{'as c'} = ['__class' => NewBehavior::class]; $this->assertNotNull($component->getBehavior('c')); + + $component->{'as d'} = function () { + return new NewBehavior(); + }; + $this->assertNotNull($component->getBehavior('d')); } public function testAttachBehaviors()