fix: handle invalid JSON gracefully in FlasherComponent

The json_decode() with JSON_THROW_ON_ERROR throws an exception before
the ?: operator can provide a fallback value. This caused page crashes
when invalid JSON was passed to the Blade component attributes.

Now using a helper method with try-catch to safely decode JSON and
return an empty array on failure, preventing page crashes.
This commit is contained in:
Younes ENNAJI
2026-03-01 20:00:16 +00:00
parent 9e7bb17faa
commit 5202c86107
2 changed files with 66 additions and 2 deletions
+22 -2
View File
@@ -15,11 +15,31 @@ final class FlasherComponent extends Component
public function render(): string
{
/** @var array<string, mixed> $criteria */
$criteria = json_decode($this->criteria, true, 512, \JSON_THROW_ON_ERROR) ?: [];
$criteria = $this->decodeJson($this->criteria);
/** @var array<string, mixed> $context */
$context = json_decode($this->context, true, 512, \JSON_THROW_ON_ERROR) ?: [];
$context = $this->decodeJson($this->context);
return app('flasher')->render('html', $criteria, $context);
}
/**
* Safely decode JSON string, returning empty array on failure.
*
* @return array<string, mixed>
*/
private function decodeJson(string $json): array
{
if ('' === $json) {
return [];
}
try {
$decoded = json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
return \is_array($decoded) ? $decoded : [];
} catch (\JsonException) {
return [];
}
}
}