Skip to content

Commit

Permalink
Attach behavior via "as foo" with Closure
Browse files Browse the repository at this point in the history
  • Loading branch information
timkelty committed Aug 22, 2024
1 parent 5abe83e commit cc05f92
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
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));

Check warning on line 194 in framework/base/Component.php

View check run for this annotation

Codecov / codecov/patch

framework/base/Component.php#L194

Added line #L194 was not covered by tests
} 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)) {
Expand Down
5 changes: 5 additions & 0 deletions tests/framework/base/ComponentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit cc05f92

Please sign in to comment.