diff --git a/src/Laravel/Component/FlasherComponent.php b/src/Laravel/Component/FlasherComponent.php index 33f5ea1c..685c25cb 100644 --- a/src/Laravel/Component/FlasherComponent.php +++ b/src/Laravel/Component/FlasherComponent.php @@ -15,11 +15,31 @@ final class FlasherComponent extends Component public function render(): string { /** @var array $criteria */ - $criteria = json_decode($this->criteria, true, 512, \JSON_THROW_ON_ERROR) ?: []; + $criteria = $this->decodeJson($this->criteria); /** @var array $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 + */ + 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 []; + } + } } diff --git a/tests/Laravel/Component/FlasherComponentTest.php b/tests/Laravel/Component/FlasherComponentTest.php index 31e79614..5d7be32b 100644 --- a/tests/Laravel/Component/FlasherComponentTest.php +++ b/tests/Laravel/Component/FlasherComponentTest.php @@ -38,4 +38,48 @@ final class FlasherComponentTest extends TestCase $actualResult = $this->flasherComponent->render(); $this->assertSame($expectedResult, $actualResult); } + + public function testRenderWithInvalidJsonCriteriaDoesNotThrow(): void + { + // Invalid JSON should not throw exception - should gracefully return empty array + $component = new FlasherComponent('{"invalid json', '{}'); + + // Should not throw JsonException + $result = $component->render(); + + $this->assertSame('Your expected result', $result); + } + + public function testRenderWithInvalidJsonContextDoesNotThrow(): void + { + // Invalid JSON should not throw exception - should gracefully return empty array + $component = new FlasherComponent('{}', '{"invalid json'); + + // Should not throw JsonException + $result = $component->render(); + + $this->assertSame('Your expected result', $result); + } + + public function testRenderWithEmptyStringsDoesNotThrow(): void + { + // Empty strings should be handled gracefully + $component = new FlasherComponent('', ''); + + // Should not throw JsonException + $result = $component->render(); + + $this->assertSame('Your expected result', $result); + } + + public function testRenderWithNonArrayJsonReturnsEmptyArray(): void + { + // Non-array JSON values should return empty array + $component = new FlasherComponent('"just a string"', '123'); + + // Should not throw and should use empty arrays + $result = $component->render(); + + $this->assertSame('Your expected result', $result); + } }