Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Identifier;
/** * Parses and validates AT Protocol handles. * * @api */final class HandleParser {
private const MAX_LENGTH = 253;
/** * @var string[] */ private const DISALLOWED_RESOLUTION_TLDS = [ 'alt', 'arpa', 'example', 'internal', 'invalid', 'local', 'localhost', 'onion', ];
/** * Parses and normalizes an AT Protocol handle. * * @throws \InvalidArgumentException * Thrown when the handle syntax is invalid. */ public function parse(string $value): Handle { $normalized = $this->normalizeInput($value); if (!$this->isValid($normalized)) { throw new \InvalidArgumentException(\sprintf('Invalid handle "%s".', $value)); }
return new Handle($normalized, \explode('.', $normalized)); }
/** * Returns whether the value is a valid handle. */ public function isValid(string $value): bool { $normalized = $this->normalizeInput($value); if ($normalized === '' || \strlen($normalized) > self::MAX_LENGTH) { return FALSE; } return ( \preg_match( '/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/', $normalized, ) === 1 ); }
/** * Returns whether the handle syntax is eligible for resolution. */ public function isResolvableSyntax(string $value, bool $allow_test_tld = FALSE): bool { if (!$this->isValid($value)) { return FALSE; }
$labels = \explode('.', $this->normalizeInput($value)); $tld = \end($labels); if ($tld === 'test') { return $allow_test_tld; } return !\in_array($tld, self::DISALLOWED_RESOLUTION_TLDS, TRUE); }
/** * Returns the normalized supplied value. */ public function normalize(string $value): string { return $this->parse($value)->value; }
private static function normalizeInput(string $value): string { return \strtolower($value); }
}