Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Lexicon\Schema;
use Wotnak\Atproto\Lexicon\ValidationContext;
/** * Validates XRPC query parameters. * * @api */final class ParamsSchema extends AbstractSchema {
/** * @param array<string, \Wotnak\Atproto\Lexicon\Schema\SchemaInterface> $properties * @param list<string> $required */ public function __construct( private readonly array $properties, private readonly array $required = [], ) {}
/** * Validates the value. */ public function validateValue(mixed $value, ValidationContext $context): mixed { if (!\is_array($value) || \array_is_list($value) && $value !== []) { $context->addViolation('Expected parameters object.', 'invalid_type'); return $value; }
$result = $value; foreach ($value as $name => $parameter) { if (!\is_string($name) || $name === '' || \preg_match('//u', $name) !== 1) { $context->addViolation('Parameter names must be non-empty UTF-8 strings.', 'invalid_parameter_name'); continue; } if (!\array_key_exists($name, $this->properties) && !self::isParameterValue($parameter)) { $context->withPath($name, static fn (ValidationContext $child) => $child->addViolation( 'Expected a scalar parameter or a homogeneous array of scalar values.', 'invalid_parameter', )); } }
foreach ($this->properties as $name => $schema) { $exists = \array_key_exists($name, $value); if (!$exists) { if ($context->options->mode === 'parse' && $schema instanceof DefaultValueSchemaInterface) { $default = $schema->defaultValue(); if ($default !== NULL) { $result[$name] = $context->withPath( $name, static fn (ValidationContext $child) => $schema->validateValue(NULL, $child), ); continue; } } if (\in_array($name, $this->required, TRUE)) { $context->withPath($name, static fn (ValidationContext $child) => $child->addViolation( 'Required parameter is missing.', 'missing_required', )); } continue; }
$validated = $context->withPath($name, static fn (ValidationContext $child) => $schema->validateValue( $value[$name], $child, )); if ($context->options->mode === 'parse' && $validated !== $value[$name]) { $result[$name] = $validated; } }
return $result; }
private static function isParameterValue(mixed $value): bool { if (\is_string($value) || \is_int($value) || \is_bool($value)) { return TRUE; } if (!\is_array($value) || !\array_is_list($value)) { return FALSE; } if ($value === []) { return TRUE; }
$first = $value[0]; if (!(\is_string($first) || \is_int($first) || \is_bool($first))) { return FALSE; } foreach ($value as $item) { if (\gettype($item) !== \gettype($first)) { return FALSE; } } return TRUE; }
}