Skip to content

Commit

Permalink
Merge pull request #20248 from timkelty/feature/attach-behaviors-with…
Browse files Browse the repository at this point in the history
…-closure

Attach behavior via "as behaviorName" with Closure
  • Loading branch information
mtangoo authored Sep 26, 2024
2 parents eb304e7 + 8724ba3 commit 3c75ff1
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 0 deletions.
1 change: 1 addition & 0 deletions framework/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
--------------------
Expand Down
2 changes: 2 additions & 0 deletions framework/base/Component.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
6 changes: 6 additions & 0 deletions tests/framework/base/ComponentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 3c75ff1

Please sign in to comment.