Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 9 additions & 71 deletions src/SchemaProcessor/PostProcessor/EnumPostProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@
use PHPModelGenerator\ModelGenerator;
use PHPModelGenerator\PropertyProcessor\Filter\FilterProcessor;
use PHPModelGenerator\Utils\ArrayHash;
use PHPModelGenerator\Utils\NormalizedName;

/**
* Generates a PHP enum for enums from JSON schemas which are automatically mapped for properties holding the enum
*/
class EnumPostProcessor extends PostProcessor
{
use EnumTrait;

private array $generatedEnums = [];

private string $namespace;
Expand Down Expand Up @@ -67,7 +68,7 @@ public function process(Schema $schema, GeneratorConfiguration $generatorConfigu
foreach ($schema->getProperties() as $property) {
$json = $property->getJsonSchema()->getJson();

if (!isset($json['enum']) || !$this->validateEnum($property)) {
if (!isset($json['enum']) || !$this->validateEnum($property, $this->skipNonMappedEnums)) {
continue;
}

Expand Down Expand Up @@ -168,63 +169,6 @@ public function postProcess(): void
parent::postProcess();
}

/**
* @throws SchemaException
*/
private function validateEnum(PropertyInterface $property): 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 ($this->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,
));
}

private function renderEnum(
GeneratorConfiguration $generatorConfiguration,
JsonSchema $jsonSchema,
Expand All @@ -235,20 +179,14 @@ private function renderEnum(
$cases = [];

foreach ($values as $value) {
$caseName = ucfirst(NormalizedName::from($map ? array_search($value, $map, true) : $value, $jsonSchema));

if (preg_match('/^\d/', $caseName) === 1) {
$caseName = "_$caseName";
}

$cases[$caseName] = var_export($value, true);
$cases[$this->getCaseName($value, $map, $jsonSchema)] = var_export($value, true);
}

$backedType = null;
switch ($this->getArrayTypes($values)) {
case ['string']: $backedType = 'string'; break;
case ['integer']: $backedType = 'int'; break;
}
$backedType = match ($this->getArrayTypes($values)) {
['string'] => 'string',
['integer'] => 'int',
default => null,
};

// make sure different enums with an identical name don't overwrite each other
while (in_array("$this->namespace\\$name", array_column($this->generatedEnums, 'fqcn'))) {
Expand Down
84 changes: 84 additions & 0 deletions src/SchemaProcessor/PostProcessor/EnumTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

export enum {{ name }} {
{% foreach cases as case, value %}
{{ case }} = {{ value }},
{% endforeach %}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{% foreach imports as import %}
import { {{ import.name }} } from '{{ import.path }}';
{% endforeach %}

export type {{ name }} = {
{% foreach properties as property %}
{{ property.getAttribute() }}: {{ typescriptType(property) }};
{% endforeach %}
}
Loading
Loading