From c28e2a13aeabc3e819fbed8af1a2b61bf430d52c Mon Sep 17 00:00:00 2001 From: Art4 Date: Fri, 19 Jul 2024 09:10:01 +0200 Subject: [PATCH] Add check for required properties in error objects --- CHANGELOG.md | 4 ++++ src/V1/Error.php | 4 ++++ tests/Unit/V1/ErrorTest.php | 24 ++++++++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b22d1ab..6d97d92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - Dropped support for PHP 7.4 and PHP 8.0 +### Fixed + +- Add check that an error object contains at least one of `id`, `links`, `status`, `code`, `title`, `detail`, `source` or `meta`. + ### Deprecated - `\Art4\Accessable::get()` will add `mixed` as a native return type declaration in 2.0.0, do the same in your implementation now to avoid errors. diff --git a/src/V1/Error.php b/src/V1/Error.php index cab0cd0..eb70ca2 100644 --- a/src/V1/Error.php +++ b/src/V1/Error.php @@ -33,6 +33,10 @@ protected function parse(mixed $object): void ); } + if (!property_exists($object, 'id') and !property_exists($object, 'links') and !property_exists($object, 'status') and !property_exists($object, 'code') and !property_exists($object, 'title') and !property_exists($object, 'detail') and !property_exists($object, 'source') and !property_exists($object, 'meta')) { + throw new ValidationException('An error object MUST contain at least one of: `id`, `links`, `status`, `code`, `title`, `detail`, `source` or `meta`.'); + } + if (property_exists($object, 'id')) { if (!is_string($object->id)) { throw new ValidationException( diff --git a/tests/Unit/V1/ErrorTest.php b/tests/Unit/V1/ErrorTest.php index 9bcb2b9..8d68134 100644 --- a/tests/Unit/V1/ErrorTest.php +++ b/tests/Unit/V1/ErrorTest.php @@ -161,4 +161,28 @@ public function testCreateDetailWithoutStringThrowsException(mixed $input): void $error = new Error($object, $this->manager, $this->parent); } + + /** + * An error object MAY have the following members, and MUST contain at least one of: + * - id + * - links + * - status + * - code + * - title + * - details + * - source + * - meta + */ + public function testCreateWithoutRequiredPropertiesThrowsException(): void + { + $object = new \stdClass(); + $object->description = 'error description'; + + $this->expectException(ValidationException::class); + $this->expectExceptionMessage( + 'An error object MUST contain at least one of: `id`, `links`, `status`, `code`, `title`, `detail`, `source` or `meta`.' + ); + + $error = new Error($object, $this->manager, $this->parent); + } }