-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathEnumTrait.php
More file actions
84 lines (69 loc) · 2.43 KB
/
EnumTrait.php
File metadata and controls
84 lines (69 loc) · 2.43 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
declare(strict_types=1);
namespace PHPModelGenerator\SchemaProcessor\PostProcessor;
use PHPModelGenerator\Exception\SchemaException;
use PHPModelGenerator\Model\Property\PropertyInterface;
use PHPModelGenerator\Model\SchemaDefinition\JsonSchema;
use PHPModelGenerator\Utils\NormalizedName;
/**
* Share common enum code for enum generation in different languages
*/
trait EnumTrait
{
/**
* @throws SchemaException
*/
private function validateEnum(PropertyInterface $property, bool $skipNonMappedEnums = false): bool
{
$throw = function (string $message) use ($property): void {
throw new SchemaException(
sprintf(
$message,
$property->getName(),
$property->getJsonSchema()->getFile(),
)
);
};
$json = $property->getJsonSchema()->getJson();
$types = $this->getArrayTypes($json['enum']);
// the enum must contain either only string values or provide a value map to resolve the values
if ($types !== ['string'] && !isset($json['enum-map'])) {
if ($skipNonMappedEnums) {
return false;
}
$throw('Unmapped enum %s in file %s');
}
if (isset($json['enum-map'])) {
asort($json['enum']);
if (is_array($json['enum-map'])) {
asort($json['enum-map']);
}
if (!is_array($json['enum-map'])
|| $this->getArrayTypes(array_keys($json['enum-map'])) !== ['string']
|| count(array_uintersect(
$json['enum-map'],
$json['enum'],
fn($a, $b): int => $a === $b ? 0 : 1,
)) !== count($json['enum'])
) {
$throw('invalid enum map %s in file %s');
}
}
return true;
}
private function getArrayTypes(array $array): array
{
return array_unique(array_map(
static fn($item): string => gettype($item),
$array,
));
}
protected function getCaseName(mixed $value, ?array $map, JsonSchema $jsonSchema): string
{
$caseName = ucfirst(NormalizedName::from($map ? array_search($value, $map, true) : $value, $jsonSchema));
if (preg_match('/^\d/', $caseName) === 1) {
$caseName = "_$caseName";
}
return $caseName;
}
}