Merge pull request #20248 from timkelty/feature/attach-behaviors-with-closure

Attach behavior via "as behaviorName" with Closure
This commit is contained in:
Stefano D. Mtangoo
2024-09-26 04:51:51 +03:00
committed by GitHub
3 changed files with 9 additions and 0 deletions

View File

@ -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
--------------------

View File

@ -190,6 +190,8 @@ class Component extends BaseObject
$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)) {

View File

@ -366,6 +366,12 @@ class ComponentTest extends TestCase
} 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()