$refs */ public function __construct( private readonly SchemaCompiler $compiler, private readonly array $refs, private readonly string $baseNsid, private readonly bool $closed = FALSE, private readonly DataModelValidator $dataModelValidator = new DataModelValidator(), ) {} /** * Validates the value. */ public function validateValue(mixed $value, ValidationContext $context): mixed { $nativeObject = $value instanceof \stdClass; $object = $nativeObject ? \get_object_vars($value) : $value; if (!\is_array($object) || !$nativeObject && \array_is_list($object) || !\is_string($object['$type'] ?? NULL)) { $context->addViolation('Expected object with a string $type property.', 'missing_type'); return $value; } $type = $object['$type']; $matchedRef = NULL; foreach ($this->refs as $ref) { $normalized = $this->compiler->normalizeRef($ref, $this->baseNsid); $discriminator = \str_ends_with($normalized, '#main') ? \substr($normalized, 0, -5) : $normalized; if ($discriminator === $type) { $matchedRef = $normalized; break; } } if ($matchedRef === NULL) { if ($this->closed) { $context->addViolation('$type is not one of the allowed union refs.', 'invalid_union_type'); } else { $this->dataModelValidator->validate($value, $context); } return $value; } $schema = $this->compiler->compileRef($matchedRef, $this->baseNsid); if (!$schema instanceof SchemaInterface) { $context->addViolation(\sprintf('Unable to resolve union ref "%s".', $matchedRef), 'unresolved_ref'); return $value; } return $schema->validateValue($value, $context); } }