-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathValidResourceAssertion.php
49 lines (40 loc) · 1.49 KB
/
ValidResourceAssertion.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
declare(strict_types=1);
namespace Undabot\JsonApi\Util;
use Undabot\JsonApi\Util\Exception\ValidationException;
/**
* @internal
*
* @psalm-suppress UnusedClass
*/
final class ValidResourceAssertion
{
/**
* @param array<string,mixed> $resource
*
* @throws ValidationException
*/
public static function assert(array $resource): void
{
// `type` is only required member, `id` is not required when creating a resource without client-generated ID
JsonApiAssertion::keyIsset($resource, 'type', 'Resource must have key `type`');
// According to the JSON:API specification, these are the only allowed keys
$allowedKeys = ['type', 'id', 'links', 'meta', 'attributes', 'relationships'];
// Assert that there are only whitelisted keys present
$disallowedKeys = array_diff(array_keys($resource), $allowedKeys);
JsonApiAssertion::count(
$disallowedKeys,
0,
sprintf('Resource can only have keys: %s', implode(', ', $allowedKeys))
);
JsonApiAssertion::string($resource['type'], 'Resource `type` must be string');
// Id is optional for resources sent in POST requests
if (true === \array_key_exists('id', $resource)) {
JsonApiAssertion::string($resource['id'], 'Resource `id` must be string');
}
// @todo validate attributes
// @todo validate relationships
// @todo valdiate links
// @todo validate meta
}
}