You've already forked php-flasher
mirror of
https://github.com/php-flasher/php-flasher.git
synced 2026-04-05 12:32:55 +01:00
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:
@@ -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 [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user