Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Lexicon;
use Wotnak\Atproto\Identifier\NsidParser;use Wotnak\Atproto\Lexicon\Schema\ArraySchema;use Wotnak\Atproto\Lexicon\Schema\BlobSchema;use Wotnak\Atproto\Lexicon\Schema\BooleanSchema;use Wotnak\Atproto\Lexicon\Schema\BytesSchema;use Wotnak\Atproto\Lexicon\Schema\CidLinkSchema;use Wotnak\Atproto\Lexicon\Schema\IntegerSchema;use Wotnak\Atproto\Lexicon\Schema\ObjectSchema;use Wotnak\Atproto\Lexicon\Schema\ParamsSchema;use Wotnak\Atproto\Lexicon\Schema\RecordSchema;use Wotnak\Atproto\Lexicon\Schema\RefSchema;use Wotnak\Atproto\Lexicon\Schema\SchemaInterface;use Wotnak\Atproto\Lexicon\Schema\StringSchema;use Wotnak\Atproto\Lexicon\Schema\TokenSchema;use Wotnak\Atproto\Lexicon\Schema\UnionSchema;use Wotnak\Atproto\Lexicon\Schema\UnknownSchema;
/** * Compiles parsed Lexicon definitions into runtime schema validators. * * @api */final class SchemaCompiler {
/** * @var array<string, \Wotnak\Atproto\Lexicon\Schema\SchemaInterface> */ private array $cache = [];
public function __construct( private readonly LexiconRepositoryInterface $repository, private readonly NsidParser $nsidParser = new NsidParser(), private readonly bool $validateUnknownDataModel = FALSE, ) {}
/** * Compiles a Lexicon record definition. */ public function compileRecord(string $collection): ?RecordSchema { $schema = $this->compileRef($collection, $collection); return $schema instanceof RecordSchema ? $schema : NULL; }
/** * Compiles a Lexicon query or procedure definition. */ public function compileXrpc(string $method): ?CompiledXrpcMethod { if (!$this->nsidParser->isValid($method)) { return NULL; } $id = $this->nsidParser->normalize($method); $document = $this->repository->getDocument($id); $definition = $document?->def('main'); if ($document === NULL || $definition === NULL) { return NULL; } $type = self::schemaType($definition); if (!\in_array($type, ['query', 'procedure'], TRUE)) { return NULL; }
$parameters = \is_array($definition['parameters'] ?? NULL) ? $this->compileParams($document, self::schemaArray($definition['parameters'])) : NULL; [$input, $inputEncoding] = $this->compileBody($document, $definition['input'] ?? NULL); [$output, $outputEncoding] = $this->compileBody($document, $definition['output'] ?? NULL); $errors = []; foreach (\is_array($definition['errors'] ?? NULL) ? $definition['errors'] : [] as $error) { if (!\is_array($error) || !\is_string($error['name'] ?? NULL)) { continue; } $errors[] = $error['name']; } return new CompiledXrpcMethod( $id, $type, $parameters, $input, $inputEncoding, $output, $outputEncoding, $errors, ); }
/** * Compiles a Lexicon reference. */ public function compileRef(string $ref, string $baseNsid): ?SchemaInterface { $normalized = $this->normalizeRef($ref, $baseNsid); if (isset($this->cache[$normalized])) { return $this->cache[$normalized]; }
[$nsid, $defName] = $this->splitRef($normalized); $document = $this->repository->getDocument($nsid); if ($document === NULL || $document->id !== $nsid) { return NULL; } $def = $document->def($defName); if ($def === NULL) { return NULL; } $type = self::schemaType($def); if (!\in_array( $type, [ 'array', 'blob', 'boolean', 'bytes', 'cid-link', 'integer', 'object', 'record', 'ref', 'string', 'token', 'union', 'unknown', ], TRUE, )) { return NULL; }
return $this->cache[$normalized] = $this->compileDefinition($document, $defName, $def); }
/** * Resolves a Lexicon reference against its base NSID. */ public function normalizeRef(string $ref, string $baseNsid): string { if (\str_starts_with($ref, 'lex:')) { $ref = \substr($ref, 4); } if (\str_starts_with($ref, '#')) { return $this->nsidParser->normalize($baseNsid) . $ref; } if (!\str_contains($ref, '#')) { return $this->nsidParser->normalize($ref) . '#main'; } [$nsid, $defName] = \explode('#', $ref, 2); return $this->nsidParser->normalize($nsid) . '#' . ($defName !== '' ? $defName : 'main'); }
/** * @return array{string, string} */ private static function splitRef(string $ref): array { [$nsid, $defName] = \explode('#', $ref, 2); return [$nsid, $defName !== '' ? $defName : 'main']; }
/** * @param array<string, mixed> $def */ private function compileDefinition(LexiconDocument $document, string $defName, array $def): SchemaInterface { if (\in_array($def['type'] ?? NULL, ['token'], TRUE)) { return new TokenSchema($document->id . ($defName === 'main' ? '' : '#' . $defName)); } if (($def['type'] ?? NULL) === 'record') { $record = self::requiredSchema($def, 'record', 'Record definition is missing its record schema.'); if (($record['type'] ?? NULL) !== 'object') { throw new \InvalidArgumentException('Record definition record schema must have type "object".'); } $key = $def['key'] ?? NULL; if (!\is_string($key) || $key === '') { throw new \InvalidArgumentException('Record definition is missing its key type.'); } return new RecordSchema( $document->id, $key, $this->compileObject($document, $record), ); }
return $this->compileSchema($document, $def); }
/** * Compiles an inline Lexicon schema. * * @param array<string, mixed> $def */ public function compileSchema(LexiconDocument $document, array $def): SchemaInterface { $type = self::schemaType($def); if ($type === NULL) { throw new \InvalidArgumentException('Lexicon schema is missing its type.'); } return match ($type) { 'object' => $this->compileObject($document, $def), 'params' => $this->compileParams($document, $def), 'array' => new ArraySchema( $this->compileSchema( $document, self::requiredSchema($def, 'items', 'Array schema is missing its item schema.'), ), \is_int($def['minLength'] ?? NULL) ? $def['minLength'] : NULL, \is_int($def['maxLength'] ?? NULL) ? $def['maxLength'] : NULL, ), 'ref' => new RefSchema( $this, self::requiredString($def, 'ref', 'Ref schema is missing its reference.'), $document->id, ), 'union' => new UnionSchema( $this, \is_array($def['refs'] ?? NULL) ? \array_values(\array_filter($def['refs'], 'is_string')) : [], $document->id, \is_bool($def['closed'] ?? NULL) ? $def['closed'] : FALSE, ), 'boolean' => new BooleanSchema( \is_bool($def['const'] ?? NULL) ? $def['const'] : NULL, \is_bool($def['default'] ?? NULL) ? $def['default'] : NULL, ), 'integer' => new IntegerSchema( \is_int($def['minimum'] ?? NULL) ? $def['minimum'] : NULL, \is_int($def['maximum'] ?? NULL) ? $def['maximum'] : NULL, \is_array($def['enum'] ?? NULL) ? \array_values(\array_filter($def['enum'], 'is_int')) : NULL, \is_int($def['const'] ?? NULL) ? $def['const'] : NULL, \is_int($def['default'] ?? NULL) ? $def['default'] : NULL, ), 'string' => new StringSchema( \is_string($def['format'] ?? NULL) ? $def['format'] : NULL, \is_int($def['minLength'] ?? NULL) ? $def['minLength'] : NULL, \is_int($def['maxLength'] ?? NULL) ? $def['maxLength'] : NULL, \is_int($def['minGraphemes'] ?? NULL) ? $def['minGraphemes'] : NULL, \is_int($def['maxGraphemes'] ?? NULL) ? $def['maxGraphemes'] : NULL, \is_array($def['enum'] ?? NULL) ? \array_values(\array_filter($def['enum'], 'is_string')) : NULL, \is_string($def['const'] ?? NULL) ? $def['const'] : NULL, \is_string($def['default'] ?? NULL) ? $def['default'] : NULL, ), 'cid-link' => new CidLinkSchema(), 'bytes' => new BytesSchema( \is_int($def['minLength'] ?? NULL) ? $def['minLength'] : NULL, \is_int($def['maxLength'] ?? NULL) ? $def['maxLength'] : NULL, ), 'blob' => new BlobSchema( \is_array($def['accept'] ?? NULL) ? \array_values(\array_filter($def['accept'], 'is_string')) : [], \is_int($def['maxSize'] ?? NULL) ? $def['maxSize'] : NULL, ), 'unknown' => new UnknownSchema(), default => throw new \InvalidArgumentException(\sprintf('Unsupported Lexicon schema type "%s".', $type)), }; }
/** * @param array<string, mixed> $def */ private function compileObject(LexiconDocument $document, array $def): ObjectSchema { $properties = []; foreach (\is_array($def['properties'] ?? NULL) ? $def['properties'] : [] as $field => $propertyDef) { if (!(\is_string($field) && \is_array($propertyDef))) { continue; }
$properties[$field] = $this->compileSchema($document, $this->schemaArray($propertyDef)); } return new ObjectSchema( properties: $properties, required: \is_array($def['required'] ?? NULL) ? \array_values(\array_filter($def['required'], 'is_string')) : [], nullable: \is_array($def['nullable'] ?? NULL) ? \array_values(\array_filter($def['nullable'], 'is_string')) : [], validateUnknownDataModel: $this->validateUnknownDataModel, ); }
/** * @param array<string, mixed> $def */ private function compileParams(LexiconDocument $document, array $def): ParamsSchema { $properties = []; foreach (\is_array($def['properties'] ?? NULL) ? $def['properties'] : [] as $name => $propertyDef) { if (!(\is_string($name) && \is_array($propertyDef))) { continue; }
$properties[$name] = $this->compileSchema($document, $this->schemaArray($propertyDef)); } return new ParamsSchema( $properties, \is_array($def['required'] ?? NULL) ? \array_values(\array_filter($def['required'], 'is_string')) : [], ); }
/** * @return array{\Wotnak\Atproto\Lexicon\Schema\SchemaInterface|null, string|null} */ private function compileBody(LexiconDocument $document, mixed $body): array { if (!\is_array($body)) { return [NULL, NULL]; } $encoding = \is_string($body['encoding'] ?? NULL) ? $body['encoding'] : NULL; if (!\is_array($body['schema'] ?? NULL)) { return [NULL, $encoding]; } return [$this->compileSchema($document, self::schemaArray($body['schema'])), $encoding]; }
/** * @param array<array-key, mixed> $schema * @return array<string, mixed> */ private static function schemaArray(array $schema): array { /** @var array<string, mixed> $schema */ return $schema; }
/** * @param array<string, mixed> $schema */ private static function schemaType(array $schema): ?string { $type = $schema['type'] ?? NULL; if (\is_string($type)) { return $type; } return \is_string($schema['ref'] ?? NULL) ? 'ref' : NULL; }
/** * @param array<string, mixed> $schema * @return array<string, mixed> */ private static function requiredSchema(array $schema, string $field, string $message): array { if (!\is_array($schema[$field] ?? NULL)) { throw new \InvalidArgumentException($message); } return self::schemaArray($schema[$field]); }
/** * @param array<string, mixed> $schema */ private static function requiredString(array $schema, string $field, string $message): string { if (!\is_string($schema[$field] ?? NULL) || $schema[$field] === '') { throw new \InvalidArgumentException($message); } return $schema[$field]; }
}