-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
ElaoEnumType.php
58 lines (48 loc) · 1.46 KB
/
ElaoEnumType.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
50
51
52
53
54
55
56
57
58
<?php
/*
* This file is part of the "elao/enum" package.
*
* Copyright (C) Elao
*
* @author Elao <contact@elao.com>
*/
namespace Elao\Enum\Bridge\ApiPlatform\Core\JsonSchema\Type;
use ApiPlatform\Core\JsonSchema\Schema;
use ApiPlatform\Core\JsonSchema\TypeFactoryInterface;
use Elao\Enum\EnumInterface;
use Symfony\Component\PropertyInfo\Type;
final class ElaoEnumType implements TypeFactoryInterface
{
/** @var TypeFactoryInterface */
private $decorated;
public function __construct(TypeFactoryInterface $decorated)
{
$this->decorated = $decorated;
}
/**
* {@inheritdoc}
*/
public function getType(Type $type, string $format = 'json', ?bool $readableLink = null, ?array $serializerContext = null, Schema $schema = null): array
{
if (!is_a($enumClass = $type->getClassName(), EnumInterface::class, true)) {
return $this->decorated->getType($type, $format, $readableLink, $serializerContext, $schema);
}
$schema = [];
$values = $enumClass::values();
$enumSchema = [
'type' => 'string',
'enum' => $values,
'example' => $values[0],
];
if ($type->isCollection()) {
$schema['type'] = 'array';
$schema['items'] = $enumSchema;
} else {
$schema = $enumSchema;
}
if ($type->isNullable()) {
$schema['nullable'] = true;
}
return $schema;
}
}