Skip to content

Commit

Permalink
Add check for required properties in error objects
Browse files Browse the repository at this point in the history
  • Loading branch information
Art4 committed Jul 19, 2024
1 parent 0d952d6 commit c28e2a1
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions src/V1/Error.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
24 changes: 24 additions & 0 deletions tests/Unit/V1/ErrorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit c28e2a1

Please sign in to comment.