nsidParser->isValid($id)) { return NULL; } $id = $this->nsidParser->normalize($id); $cacheKey = CacheKey::build($this->cacheKeyPrefix, $id); $cached = $this->cache?->get($cacheKey); if (\is_array($cached)) { /** @var array $cached */ $document = $this->parseVerifiedSchema($cached, $id); if ($document !== NULL) { return $document; } } $publisherDid = $this->resolvePublisherDid($id); if ($publisherDid === NULL) { return NULL; } $didDocument = $this->didResolver->resolveDocument($publisherDid); $pds = $didDocument?->getPdsEndpoint(); if ($pds === NULL) { return NULL; } try { $response = $this->xrpcClient->get( 'com.atproto.repo.getRecord', [ 'repo' => $publisherDid, 'collection' => 'com.atproto.lexicon.schema', 'rkey' => $id, ], new XrpcOptions(serviceUrl: $pds, maxResponseBytes: 1_048_576), ); } catch (XrpcException) { return NULL; } catch (\InvalidArgumentException) { return NULL; } $schema = $this->verifyRecordResponse($response, $publisherDid, $id); if ($schema === NULL) { return NULL; } $document = $this->parseVerifiedSchema($schema, $id); if ($document === NULL) { return NULL; } $this->cache?->set($cacheKey, $schema, $this->cacheTtl); return $document; } private function resolvePublisherDid(string $nsid): ?string { $segments = \explode('.', $nsid); \array_pop($segments); $dnsName = '_lexicon.' . \implode('.', \array_reverse($segments)); $dids = []; foreach ($this->dnsTxtResolver->resolveTxt($dnsName) as $record) { if (!\str_starts_with($record, 'did=')) { continue; } $did = \substr($record, 4); if (!DidParser::isValid($did) || !$this->didParser->isSupported($did)) { return NULL; } $dids[$did] = TRUE; } return \count($dids) === 1 ? \array_key_first($dids) : NULL; } /** * @param array $response * @return array|null */ private function verifyRecordResponse(array $response, string $publisherDid, string $nsid): ?array { if ( !\is_string($response['uri'] ?? NULL) || !\is_string($response['cid'] ?? NULL) || !$this->cidParser->isValid($response['cid']) || !\is_array($response['value'] ?? NULL) ) { return NULL; } try { $uri = $this->atUriParser->parse($response['uri']); } catch (\InvalidArgumentException) { return NULL; } if ( $uri->repo !== $publisherDid || $uri->collection !== 'com.atproto.lexicon.schema' || $uri->rkey !== $nsid ) { return NULL; } /** @var array $schema */ $schema = $response['value']; if (($schema['$type'] ?? NULL) !== 'com.atproto.lexicon.schema') { return NULL; } unset($schema['$type']); return $schema; } /** * @param array $schema */ private function parseVerifiedSchema(array $schema, string $nsid): ?LexiconDocument { $result = $this->lexiconParser->parse($schema); return $result->value instanceof LexiconDocument && $result->value->id === $nsid ? $result->value : NULL; } }