Skip to content

Commit 7d27e54

Browse files
authored
Merge pull request #32576 from laravel/parent-attributes
Properly Inherit Parent Attributes
2 parents ffe8ace + fd16a0d commit 7d27e54

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

src/Illuminate/View/Compilers/Concerns/CompilesComponents.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Illuminate\View\Compilers\Concerns;
44

55
use Illuminate\Support\Str;
6+
use Illuminate\View\ComponentAttributeBag;
67

78
trait CompilesComponents
89
{
@@ -167,7 +168,7 @@ protected function compileProps($expression)
167168
public static function sanitizeComponentAttribute($value)
168169
{
169170
return is_string($value) ||
170-
(is_object($value) && method_exists($value, '__toString'))
171+
(is_object($value) && ! $value instanceof ComponentAttributeBag && method_exists($value, '__toString'))
171172
? e($value)
172173
: $value;
173174
}

src/Illuminate/View/ComponentAttributeBag.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,15 @@ public function merge(array $attributeDefaults = [])
141141
*/
142142
public function setAttributes(array $attributes)
143143
{
144+
if (isset($attributes['attributes']) &&
145+
$attributes['attributes'] instanceof self) {
146+
$parentBag = $attributes['attributes'];
147+
148+
unset($attributes['attributes']);
149+
150+
$attributes = $parentBag->merge($attributes);
151+
}
152+
144153
$this->attributes = $attributes;
145154
}
146155

tests/View/ViewComponentTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Illuminate\Tests\View;
44

55
use Illuminate\View\Component;
6+
use Illuminate\View\ComponentAttributeBag;
67
use PHPUnit\Framework\TestCase;
78

89
class ViewComponentTest extends TestCase
@@ -18,6 +19,15 @@ public function testDataExposure()
1819
$this->assertSame('taylor', $variables['hello']('taylor'));
1920
}
2021

22+
public function testAttributeParentInheritance()
23+
{
24+
$component = new TestViewComponent;
25+
26+
$component->withAttributes(['class' => 'foo', 'attributes' => new ComponentAttributeBag(['class' => 'bar', 'type' => 'button'])]);
27+
28+
$this->assertEquals('class="foo bar" type="button"', (string) $component->attributes);
29+
}
30+
2131
public function testPublicMethodsWithNoArgsAreConvertedToStringableCallablesInvokedAndNotCached()
2232
{
2333
$component = new TestSampleViewComponent;

0 commit comments

Comments
 (0)