keySchema = self::createKeySchema($key); } /** * 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)) { $context->addViolation('Record must be an object.', 'invalid_type'); return $value; } $type = $object['$type'] ?? NULL; if (!\is_string($type)) { $context->addViolationAt('$type', 'Record $type must be a string.', 'missing_type'); } if (\is_string($type) && $type !== $this->collection) { $context->addViolationAt( '$type', \sprintf('Expected "%s", got "%s".', $this->collection, $type), 'type_mismatch', ); } return $this->record->validateValue($value, $context); } /** * Creates a repository record with the schema type discriminator. * * @param array $data * * @return array */ public function build(array $data): array { return ['$type' => $this->collection] + $data; } /** * Returns the record-key strategy. */ public function key(): string { return $this->key; } /** * Returns the literal record key for a literal-key strategy. */ public function keySchema(): StringSchema { return $this->keySchema; } /** * Returns whether a record key satisfies this schema. */ public function validateKey(mixed $value, ?ValidationOptions $options = NULL): ValidationResult { return $this->keySchema->safeValidate($value, $options); } private static function createKeySchema(string $key): StringSchema { if ($key === 'any') { return new StringSchema(format: 'record-key'); } if ($key === 'tid') { return new StringSchema(format: 'tid'); } if ($key === 'nsid') { return new StringSchema(format: 'nsid'); } if (\str_starts_with($key, 'literal:')) { $literal = \substr($key, 8); if (RecordKeyParser::isValid($literal)) { return new StringSchema(const: $literal, default: $literal); } } throw new \InvalidArgumentException(\sprintf('Unsupported record key type "%s".', $key)); } }