blob: 864063f79af753dfdc2c682c3ad4682bd0d266ee (
plain) (
blame)
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
|
<?php
declare(strict_types=1);
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Serialization\Attribute\JsonSchema;
/**
* Interface for using reflection with the JSON object.
*/
trait JsonSchemaReflectionTrait {
/**
* Get a JSON Schema based on method reflection.
*
* @param object $object
* Object to reflect.
* @param string $method
* Method to reflect.
* @param array $fallback
* Fallback. Defaults to an empty array, which is a matches-all schema.
* @param bool $nullable
* If a schema is returned from reflection, whether to add a null option.
*
* @return array
* JSON Schema.
*/
protected function getJsonSchemaForMethod(mixed $object, string $method, array $fallback = [], bool $nullable = FALSE): array {
$schemas = [];
if ((is_object($object) || class_exists($object)) && method_exists($object, $method)) {
$reflection = new \ReflectionMethod($object, $method);
$schemas = $reflection->getAttributes(JsonSchema::class);
}
if (count($schemas) === 0) {
return $fallback;
}
$schemas = array_values(array_filter([
...array_map(fn ($schema) => $schema->newInstance()->getJsonSchema(), $schemas),
$nullable ? ['type' => 'null'] : NULL,
]));
return count($schemas) === 1
? current($schemas)
: ['oneOf' => $schemas];
}
}
|