Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attach behavior via "as behaviorName" with Closure #20248

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading