Skip to content

Commit f0f7dfa

Browse files
authored
[7.x] Fix output of component attributes (#31994)
* Fix output of component attributes * Add missing merge() to test
1 parent 2c8182c commit f0f7dfa

File tree

2 files changed

+23
-10
lines changed

2 files changed

+23
-10
lines changed

src/Illuminate/View/ComponentAttributeBag.php

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -113,12 +113,6 @@ public function merge(array $attributeDefaults = [])
113113
}, $attributeDefaults);
114114

115115
foreach ($this->attributes as $key => $value) {
116-
if ($value === true) {
117-
$attributes[$key] = $key;
118-
119-
continue;
120-
}
121-
122116
if ($key !== 'class') {
123117
$attributes[$key] = $value;
124118

@@ -130,7 +124,7 @@ public function merge(array $attributeDefaults = [])
130124
));
131125
}
132126

133-
return new static(array_merge($attributeDefaults, array_filter($attributes)));
127+
return new static(array_merge($attributeDefaults, $attributes));
134128
}
135129

136130
/**
@@ -230,9 +224,15 @@ public function __toString()
230224
$string = '';
231225

232226
foreach ($this->attributes as $key => $value) {
233-
$string .= $value === true
234-
? ' '.$key
235-
: ' '.$key.'="'.str_replace('"', '\\"', trim($value)).'"';
227+
if ($value === false || is_null($value)) {
228+
continue;
229+
}
230+
231+
if ($value === true) {
232+
$value = $key;
233+
}
234+
235+
$string .= ' '.$key.'="'.str_replace('"', '\\"', trim($value)).'"';
236236
}
237237

238238
return trim($string);

tests/View/ViewComponentAttributeBagTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,5 +27,18 @@ public function testAttributeRetrieval()
2727
$bag = new ComponentAttributeBag([]);
2828

2929
$this->assertSame('class="mt-4"', (string) $bag->merge(['class' => 'mt-4']));
30+
31+
$bag = new ComponentAttributeBag([
32+
'test-string' => 'ok',
33+
'test-null' => null,
34+
'test-false' => false,
35+
'test-true' => true,
36+
'test-0' => 0,
37+
'test-0-string' => '0',
38+
'test-empty-string' => '',
39+
]);
40+
41+
$this->assertSame('test-string="ok" test-true="test-true" test-0="0" test-0-string="0" test-empty-string=""', (string) $bag);
42+
$this->assertSame('test-string="ok" test-true="test-true" test-0="0" test-0-string="0" test-empty-string=""', (string) $bag->merge());
3043
}
3144
}

0 commit comments

Comments
 (0)