Something went wrong. Try again.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Lexicon\Schema;
use Wotnak\Atproto\Lexicon\DataModelValidator;use Wotnak\Atproto\Lexicon\SchemaCompiler;use Wotnak\Atproto\Lexicon\ValidationContext;
/** * Validates values against a Lexicon reference union. * * @api */final class UnionSchema extends AbstractSchema {
/** * @param list<string> $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); }
}