$properties * @param list $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; } }