Skip to content

Commit 37a2bc6

Browse files
[12.x] Fix handling of Htmlable objects in Js::convertDataToJavaScriptExpression() (#56253)
* Refine handling of `Htmlable` objects * Update Js.php --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent 5191d63 commit 37a2bc6

File tree

2 files changed

+59
-2
lines changed

2 files changed

+59
-2
lines changed

src/Illuminate/Support/Js.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,10 @@ protected function convertDataToJavaScriptExpression($data, $flags = 0, $depth =
7070
return $data->toHtml();
7171
}
7272

73-
if ($data instanceof Htmlable) {
73+
if ($data instanceof Htmlable &&
74+
! $data instanceof Arrayable &&
75+
! $data instanceof Jsonable &&
76+
! $data instanceof JsonSerializable) {
7477
$data = $data->toHtml();
7578
}
7679

tests/Support/SupportJsTest.php

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,13 +133,67 @@ public function testHtmlable()
133133
{
134134
$data = new class implements Htmlable
135135
{
136-
public function toHtml(): string
136+
public function toHtml()
137137
{
138138
return '<p>Hello, World!</p>';
139139
}
140140
};
141141

142142
$this->assertEquals("'\u003Cp\u003EHello, World!\u003C\/p\u003E'", (string) Js::from($data));
143+
144+
$data = new class implements Htmlable, Arrayable
145+
{
146+
public function toHtml()
147+
{
148+
return '<p>Hello, World!</p>';
149+
}
150+
151+
public function toArray()
152+
{
153+
return ['foo' => 'hello', 'bar' => 'world'];
154+
}
155+
};
156+
157+
$this->assertEquals(
158+
"JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
159+
(string) Js::from($data)
160+
);
161+
162+
$data = new class implements Htmlable, Jsonable
163+
{
164+
public function toHtml()
165+
{
166+
return '<p>Hello, World!</p>';
167+
}
168+
169+
public function toJson($options = 0)
170+
{
171+
return json_encode(['foo' => 'hello', 'bar' => 'world'], $options);
172+
}
173+
};
174+
175+
$this->assertEquals(
176+
"JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
177+
(string) Js::from($data)
178+
);
179+
180+
$data = new class implements Htmlable, JsonSerializable
181+
{
182+
public function toHtml()
183+
{
184+
return '<p>Hello, World!</p>';
185+
}
186+
187+
public function jsonSerialize(): mixed
188+
{
189+
return ['foo' => 'hello', 'bar' => 'world'];
190+
}
191+
};
192+
193+
$this->assertEquals(
194+
"JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
195+
(string) Js::from($data)
196+
);
143197
}
144198

145199
public function testBackedEnums()

0 commit comments

Comments
 (0)