Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Identifier;
/** * Parses AT Protocol URI strings. * * @api */final class AtUriParser {
public function __construct( private readonly DidParser $didParser = new DidParser(), private readonly HandleParser $handleParser = new HandleParser(), private readonly NsidParser $nsidParser = new NsidParser(), private readonly RecordKeyParser $recordKeyParser = new RecordKeyParser(), ) {}
/** * Parses an AT URI. * * @throws \InvalidArgumentException * Thrown when the URI is invalid. */ public function parse(string $uri): AtUri { if (!\str_starts_with($uri, AtUri::SCHEME_PREFIX)) { throw new \InvalidArgumentException(\sprintf('AT URI must start with %s.', AtUri::SCHEME_PREFIX)); } if (\str_contains($uri, '?') || \str_contains($uri, '#') || \str_contains($uri, '@')) { throw new \InvalidArgumentException('AT URI query, fragment, and userinfo sections are not supported.'); }
$path = \substr($uri, \strlen(AtUri::SCHEME_PREFIX)); $parts = \explode('/', $path); $repo = \array_shift($parts); if ($repo === '') { throw new \InvalidArgumentException('AT URI must include a repository DID or handle.'); } if (\count($parts) > 2) { throw new \InvalidArgumentException('AT URI may include only repo, collection, and rkey components.'); } if (\in_array('', $parts, TRUE)) { throw new \InvalidArgumentException('AT URI path components may not be empty.'); }
$collection = $parts[0] ?? NULL; $rkey = $parts[1] ?? NULL;
$normalized_repo = $this->normalizeRepo($repo); $normalized_collection = $collection !== NULL ? $this->nsidParser->normalize($collection) : NULL; $normalized_rkey = $rkey !== NULL ? $this->recordKeyParser->normalize($rkey) : NULL; $normalized = AtUri::SCHEME_PREFIX . $normalized_repo; if ($normalized_collection !== NULL) { $normalized .= '/' . $normalized_collection; } if ($normalized_rkey !== NULL) { $normalized .= '/' . $normalized_rkey; }
return new AtUri($normalized_repo, $normalized_collection, $normalized_rkey, $normalized); }
/** * Builds a canonical record AT URI from its components. */ public function build(string $repo, string $collection, string $rkey): string { return \sprintf( AtUri::SCHEME_PREFIX . '%s/%s/%s', $this->normalizeRepo($repo), $this->nsidParser->normalize($collection), $this->recordKeyParser->normalize($rkey), ); }
/** * Returns whether the value is a valid AT URI. */ public function isValid(string $uri): bool { try { $this->parse($uri); } catch (\InvalidArgumentException) { return FALSE; } return TRUE; }
private function normalizeRepo(string $repo): string { if ($this->didParser->isValid($repo)) { return $this->didParser->normalize($repo); } return $this->handleParser->normalize($repo); }
}