From 5dcb64a87eace70ea2204ef21ac45e83578e37c5 Mon Sep 17 00:00:00 2001 From: Caen De Silva Date: Tue, 25 Jun 2024 12:13:28 +0200 Subject: [PATCH] Throw parse exception for empty Yaml to match `json_validate` See https://github.com/hydephp/develop/issues/1736#issuecomment-2188298689 --- RELEASE_NOTES.md | 1 + .../framework/src/Support/DataCollection.php | 4 ++++ .../tests/Unit/DataCollectionUnitTest.php | 24 +++++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 73109113ac5..15cd68599a1 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -247,3 +247,4 @@ InvalidArgumentException: Invalid JSON in file: 'foo/baz.json' (Syntax error) ``` In order to normalize the thrown exceptions, we now rethrow Yaml `ParseException` as `InvalidArgumentException` to match the JSON validation. +Additionally, an exception will be thrown if a JSON or YAML file is empty, as this is unlikely to be intentional. diff --git a/packages/framework/src/Support/DataCollection.php b/packages/framework/src/Support/DataCollection.php index 21c7a728674..a551eb60c37 100644 --- a/packages/framework/src/Support/DataCollection.php +++ b/packages/framework/src/Support/DataCollection.php @@ -72,6 +72,10 @@ public static function yaml(string $name): static $content = Str::between($content, '---', '---'); try { + if (blank(trim($content))) { + throw new ParseException('File is empty'); + } + $parsed = Yaml::parse($content) ?: []; } catch (ParseException $exception) { throw new InvalidArgumentException(sprintf("Invalid YAML in file: '%s' (%s)", $file, $exception->getMessage()), previous: $exception); diff --git a/packages/framework/tests/Unit/DataCollectionUnitTest.php b/packages/framework/tests/Unit/DataCollectionUnitTest.php index 08b9ffc0404..cb64171a241 100644 --- a/packages/framework/tests/Unit/DataCollectionUnitTest.php +++ b/packages/framework/tests/Unit/DataCollectionUnitTest.php @@ -229,6 +229,30 @@ public function testYamlCollectionsThrowExceptionForInvalidYaml() MockableDataCollection::yaml('foo'); } + public function testYamlCollectionsThrowExceptionForEmptyYaml() + { + MockableDataCollection::mockFiles([ + 'foo/bar.yml' => '', + ]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage("Invalid YAML in file: 'foo/bar.yml' (File is empty)"); + + MockableDataCollection::yaml('foo'); + } + + public function testYamlCollectionsThrowExceptionForBlankYaml() + { + MockableDataCollection::mockFiles([ + 'foo/bar.yml' => ' ', + ]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage("Invalid YAML in file: 'foo/bar.yml' (File is empty)"); + + MockableDataCollection::yaml('foo'); + } + public function testYamlCollectionsThrowExceptionForOtherReasonsThanSyntaxErrorWithUtfError() { MockableDataCollection::mockFiles([