Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Lexicon\Schema;
use Wotnak\Atproto\Identifier\RecordKeyParser;use Wotnak\Atproto\Lexicon\ValidationContext;use Wotnak\Atproto\Lexicon\ValidationOptions;use Wotnak\Atproto\Lexicon\ValidationResult;
/** * Validates repository records and record keys. * * @api */final class RecordSchema extends AbstractSchema {
private readonly StringSchema $keySchema;
public function __construct( private readonly string $collection, private readonly string $key, private readonly ObjectSchema $record, ) { $this->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<string, mixed> $data * * @return array<string, mixed> */ 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)); }
}