Skip to content
Open
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
65 changes: 60 additions & 5 deletions src/JsonSchema/SchemaFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,10 @@
use Symfony\Component\TypeInfo\Type\CompositeTypeInterface;
use Symfony\Component\TypeInfo\Type\GenericType;
use Symfony\Component\TypeInfo\Type\ObjectType;
use Symfony\Component\TypeInfo\Type\UnionType;
use Symfony\Component\TypeInfo\TypeIdentifier;

/**
* {@inheritdoc}
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareInterface
Expand All @@ -57,9 +56,6 @@ public function __construct(ResourceMetadataCollectionFactoryInterface $resource
$this->resourceClassResolver = $resourceClassResolver;
}

/**
* {@inheritdoc}
*/
public function buildSchema(string $className, string $format = 'json', string $type = Schema::TYPE_OUTPUT, ?Operation $operation = null, ?Schema $schema = null, ?array $serializerContext = null, bool $forceCollection = false): Schema
{
$schema = $schema ? clone $schema : new Schema();
Expand Down Expand Up @@ -354,6 +350,65 @@ private function buildPropertySchema(Schema $schema, string $definitionName, str
$valueType = TypeHelper::getCollectionValueType($t);
}

if ($valueType instanceof UnionType) {
$unionRefs = [];

foreach ($valueType->getTypes() as $subtype) {
if ($subtype instanceof BuiltinType && TypeIdentifier::NULL === $subtype->getTypeIdentifier()) {
continue;
}

if ($subtype instanceof ObjectType) {
$className = $subtype->getClassName();
} elseif ($subtype instanceof BuiltinType && $subtype->getTypeIdentifier()->isScalar()) {
$unionRefs[] = match ($subtype->getTypeIdentifier()) {
TypeIdentifier::INT => ['type' => 'integer'],
TypeIdentifier::FLOAT => ['type' => 'number'],
TypeIdentifier::BOOL => ['type' => 'boolean'],
TypeIdentifier::TRUE => ['type' => 'boolean', 'const' => true],
TypeIdentifier::FALSE => ['type' => 'boolean', 'const' => false],
TypeIdentifier::STRING => ['type' => 'string'],
default => ['type' => 'null'],
};

continue;
} else {
continue;
}

$subSchema = new Schema($version);
$subSchema->setDefinitions($schema->getDefinitions());

$result = ($this->schemaFactory ?: $this)->buildSchema(
$className,
$format,
$parentType,
null,
$subSchema,
$serializerContext + [self::FORCE_SUBSCHEMA => true],
);

if (isset($result['$ref'])) {
$unionRefs[] = ['$ref' => $result['$ref']];
}
}

if ($unionRefs) {
if ($isCollection) {
$propertySchema['type'] = 'array';
$propertySchema['items'] = 1 === \count($unionRefs)
? $unionRefs[0]
: ['anyOf' => $unionRefs];
} else {
$refs = 1 === \count($unionRefs)
? [$unionRefs[0]]
: $unionRefs;
}
}

continue;
}

if (!$valueType instanceof ObjectType && !$valueType instanceof GenericType) {
continue;
}
Expand Down
Loading