Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Lexicon\Schema;
use Wotnak\Atproto\Identifier\AtUriParser;use Wotnak\Atproto\Identifier\CidParser;use Wotnak\Atproto\Identifier\DidParser;use Wotnak\Atproto\Identifier\HandleParser;use Wotnak\Atproto\Identifier\NsidParser;use Wotnak\Atproto\Identifier\RecordKeyParser;use Wotnak\Atproto\Lexicon\ValidationContext;
/** * Validates strings against Lexicon format and length constraints. * * @api */final class StringSchema extends AbstractSchema implements DefaultValueSchemaInterface {
/** * @param list<string>|null $enum */ public function __construct( private readonly ?string $format = NULL, private readonly ?int $minLength = NULL, private readonly ?int $maxLength = NULL, private readonly ?int $minGraphemes = NULL, private readonly ?int $maxGraphemes = NULL, private readonly ?array $enum = NULL, private readonly ?string $const = NULL, private readonly ?string $default = NULL, ) {}
/** * Validates the value. */ public function validateValue(mixed $value, ValidationContext $context): mixed { if ($value === NULL && $context->options->mode === 'parse' && $this->default !== NULL) { $value = $this->default; } if (!\is_string($value)) { $context->addViolation('Expected string.', 'invalid_type'); return $value; } if (\preg_match('//u', $value) !== 1) { $context->addViolation('String must contain valid UTF-8.', 'invalid_utf8'); return $value; } if ($this->const !== NULL && $value !== $this->const) { $context->addViolation(\sprintf('Expected "%s".', $this->const), 'invalid_const'); } if ($this->enum !== NULL && !\in_array($value, $this->enum, TRUE)) { $context->addViolation('Value is not one of the allowed enum values.', 'invalid_enum'); }
$bytes = \strlen($value); if ($this->minLength !== NULL && $bytes < $this->minLength) { $context->addViolation(\sprintf('Expected at least %d bytes.', $this->minLength), 'min_length'); } if ($this->maxLength !== NULL && $bytes > $this->maxLength) { $context->addViolation(\sprintf('Expected at most %d bytes.', $this->maxLength), 'max_length'); }
$graphemes = \grapheme_strlen($value); if (\is_int($graphemes)) { if ($this->minGraphemes !== NULL && $graphemes < $this->minGraphemes) { $context->addViolation(\sprintf('Expected at least %d graphemes.', $this->minGraphemes), 'min_graphemes'); } if ($this->maxGraphemes !== NULL && $graphemes > $this->maxGraphemes) { $context->addViolation(\sprintf('Expected at most %d graphemes.', $this->maxGraphemes), 'max_graphemes'); } }
if ($this->format !== NULL && !$this->formatIsValid($value, $context)) { $context->addViolation(\sprintf('Expected a valid %s.', $this->format), 'invalid_format'); } return $value; }
private function formatIsValid(string $value, ValidationContext $context): bool { try { return match ($this->format) { 'uri' => $this->uriIsValid($value), 'datetime' => $context->options->strict ? $this->datetimeIsValid($value) : \strtotime($value) !== FALSE, 'at-uri' => new AtUriParser()->isValid($value), 'did' => new DidParser()->isValid($value), 'handle' => new HandleParser()->isValid($value), 'at-identifier' => new DidParser()->isValid($value) || new HandleParser()->isValid($value), 'nsid' => new NsidParser()->isValid($value), 'cid' => new CidParser()->isValidGeneral($value), 'language' => $context->options->strict ? $this->strictLanguageTagIsValid($value) : $this->languageSyntaxIsValid($value), 'tid' => \preg_match('/^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/', $value) === 1, 'record-key' => new RecordKeyParser()->isValid($value), default => FALSE, }; } catch (\InvalidArgumentException) { return FALSE; } }
/** * Returns the default value declared by the schema. */ public function defaultValue(): ?string { return $this->default; }
private static function uriIsValid(string $value): bool { if ($value === '' || \strlen($value) > 8192) { return FALSE; }
$unreserved = '[A-Za-z0-9._\x7E-]'; $percentEncoded = '%[0-9A-Fa-f]{2}'; $subDelimiter = '[!$&\'()*+,;=]'; $pchar = '(?:' . $unreserved . '|' . $percentEncoded . '|' . $subDelimiter . '|[:@])'; $userInfo = '(?:' . $unreserved . '|' . $percentEncoded . '|' . $subDelimiter . '|:)*'; $regName = '(?:' . $unreserved . '|' . $percentEncoded . '|' . $subDelimiter . ')*'; $ipvFuture = 'v[0-9A-Fa-f]+\.(?:' . $unreserved . '|' . $subDelimiter . '|:)+'; $ipLiteral = '\[(?:[0-9A-Fa-f:.]+|' . $ipvFuture . ')\]'; $authority = '(?:' . $userInfo . '@)?(?:' . $ipLiteral . '|' . $regName . ')(?::[0-9]*)?'; $pathAbempty = '(?:/' . $pchar . '*)*'; $pathAbsolute = '/(?:' . $pchar . '+(?:/' . $pchar . '*)*)?'; $pathRootless = $pchar . '+(?:/' . $pchar . '*)*'; $queryOrFragment = '(?:' . $pchar . '|[/?])*'; $pattern = '~\A[A-Za-z][A-Za-z0-9+.-]*:(?://' . $authority . $pathAbempty . '|' . $pathAbsolute . '|' . $pathRootless . '|)(?:\?' . $queryOrFragment . ')?(?:#' . $queryOrFragment . ')?\z~D'; if (\preg_match($pattern, $value) !== 1) { return FALSE; }
$matches = []; if (\preg_match('/\[([^\]]+)\]/', $value, $matches) !== 1) { return TRUE; } return ( \preg_match('/\A' . $ipvFuture . '\z/D', $matches[1]) === 1 || \filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE ); }
private static function languageSyntaxIsValid(string $value): bool { $grandfathered = [ 'art-lojban', 'cel-gaulish', 'en-gb-oed', 'i-ami', 'i-bnn', 'i-default', 'i-enochian', 'i-hak', 'i-klingon', 'i-lux', 'i-mingo', 'i-navajo', 'i-pwn', 'i-tao', 'i-tay', 'i-tsu', 'no-bok', 'no-nyn', 'sgn-be-fr', 'sgn-be-nl', 'sgn-ch-de', 'zh-guoyu', 'zh-hakka', 'zh-min', 'zh-min-nan', 'zh-xiang', ]; if (\in_array(\strtolower($value), $grandfathered, TRUE)) { return TRUE; }
// RFC 5646 language-tag ABNF, excluding the grandfathered productions // handled above. Registry membership is intentionally not required. return ( \preg_match( '/\A(?:' . '(?:(?:[A-Z]{2,3}(?:-[A-Z]{3}){0,3}|[A-Z]{4}|[A-Z]{5,8})' . '(?:-[A-Z]{4})?' . '(?:-(?:[A-Z]{2}|[0-9]{3}))?' . '(?:-(?:[A-Z0-9]{5,8}|[0-9][A-Z0-9]{3}))*' . '(?:-[0-9A-WY-Z](?:-[A-Z0-9]{2,8})+)*' . '(?:-X(?:-[A-Z0-9]{1,8})+)?)' . '|(?:X(?:-[A-Z0-9]{1,8})+)' . ')\z/iD', $value, ) === 1 ); }
private static function strictLanguageTagIsValid(string $value): bool { if (!self::languageSyntaxIsValid($value)) { return FALSE; }
$variants = []; $singletons = []; foreach (\explode('-', \strtolower($value)) as $subtag) { if (\preg_match('/^(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3})$/D', $subtag) === 1) { if (isset($variants[$subtag])) { return FALSE; } $variants[$subtag] = TRUE; } if (\preg_match('/^[0-9a-wy-z]$/D', $subtag) === 1) { if (isset($singletons[$subtag])) { return FALSE; } $singletons[$subtag] = TRUE; } } return TRUE; }
private static function datetimeIsValid(string $value): bool { $matches = []; if ( \preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))$/', $value, $matches, ) !== 1 ) { return FALSE; }
$year = (int) $matches[1]; $month = (int) $matches[2]; $day = (int) $matches[3]; $hour = (int) $matches[4]; $minute = (int) $matches[5]; $second = (int) $matches[6]; $offsetSign = $matches[7] ?? NULL; $offsetHour = isset($matches[8]) ? (int) $matches[8] : 0; $offsetMinute = isset($matches[9]) ? (int) $matches[9] : 0; $daysInMonth = [ 1 => 31, 2 => ($year % 4) === 0 && (($year % 100) !== 0 || ($year % 400) === 0) ? 29 : 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30, 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31, ]; $normalizesBeforeYearZero = $year === 0 && $month === 1 && $day === 1 && $offsetSign === '+' && (($hour * 60) + $minute) < (($offsetHour * 60) + $offsetMinute);
return ( isset($daysInMonth[$month]) && $day >= 1 && $day <= $daysInMonth[$month] && $hour <= 23 && $minute <= 59 && $second <= 59 && $offsetHour <= 23 && $offsetMinute <= 59 && !($offsetSign === '-' && $offsetHour === 0 && $offsetMinute === 0) && !$normalizesBeforeYearZero ); }
}