Skip to content

Commit

Permalink
feat(parametervalidator): parameter validation
Browse files Browse the repository at this point in the history
  • Loading branch information
soyuka committed Apr 18, 2024
1 parent ba1c61f commit 1f573d0
Show file tree
Hide file tree
Showing 9 changed files with 180 additions and 7 deletions.
27 changes: 23 additions & 4 deletions src/Metadata/Parameter.php
Expand Up @@ -15,17 +15,19 @@

use ApiPlatform\OpenApi;
use ApiPlatform\State\ProviderInterface;
use Symfony\Component\Validator\Constraint;

/**
* @experimental
*/
abstract class Parameter
{
/**
* @param array{type?: string}|null $schema
* @param array<string, mixed> $extraProperties
* @param ProviderInterface|callable|string|null $provider
* @param FilterInterface|string|null $filter
* @param array{type?: string}|null $schema
* @param array<string, mixed> $extraProperties
* @param ProviderInterface|callable|string|null $provider
* @param FilterInterface|string|null $filter
* @param Symfony\Component\Validator\Constraint|string|null $constraint
*/
public function __construct(
protected ?string $key = null,
Expand All @@ -37,6 +39,7 @@ public function __construct(
protected ?string $description = null,
protected ?bool $required = null,
protected ?int $priority = null,
protected array|Constraint|null $constraint = null,
protected ?array $extraProperties = [],
) {
}
Expand Down Expand Up @@ -89,6 +92,14 @@ public function getPriority(): ?int
return $this->priority;
}

/**
* @return Constraint|Constraint[]|null
*/
public function getConstraint(): array|Constraint|null
{
return $this->constraint;
}

/**
* @return array<string, mixed>
*/
Expand Down Expand Up @@ -178,6 +189,14 @@ public function withRequired(bool $required): static
return $self;
}

public function withConstraint(array|Constraint $constraint): static
{
$self = clone $this;
$self->constraint = $constraint;

return $self;
}

/**
* @param array<string, mixed> $extraProperties
*/
Expand Down
Expand Up @@ -21,6 +21,11 @@
use ApiPlatform\OpenApi;
use ApiPlatform\Serializer\Filter\FilterInterface as SerializerFilterInterface;
use Psr\Container\ContainerInterface;
use Symfony\Component\Validator\Constraints\GreaterThan;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Constraints\LessThan;
use Symfony\Component\Validator\Constraints\LessThanOrEqual;
use Symfony\Component\Validator\Constraints\Range;

/**
* Prepares Parameters documentation by reading its filter details and declaring an OpenApi parameter.
Expand Down Expand Up @@ -96,20 +101,25 @@ private function setDefaults(string $key, Parameter $parameter, string $resource
$parameter = $parameter->withSchema($schema);
}

if (null === $parameter->getProperty() && ($property = $description[$key]['property'] ?? null)) {
$parameter = $parameter->withProperty($property);
}

if (null === $parameter->getOpenApi() && $openApi = $description[$key]['openapi'] ?? null) {
if ($openApi instanceof OpenApi\Model\Parameter) {
$parameter = $parameter->withOpenApi($openApi);
}

if (\is_array($openApi)) {
$schema = $schema ?? $openapi['schema'] ?? [];
$parameter = $parameter->withOpenApi(new OpenApi\Model\Parameter(
$key,
$parameter instanceof HeaderParameterInterface ? 'header' : 'query',
$description[$key]['description'] ?? '',
$description[$key]['required'] ?? $openApi['required'] ?? false,
$openApi['deprecated'] ?? false,
$openApi['allowEmptyValue'] ?? true,
$schema ?? $openApi['schema'] ?? [],
$schema,
$openApi['style'] ?? null,
$openApi['explode'] ?? ('array' === ($schema['type'] ?? null)),
$openApi['allowReserved'] ?? false,
Expand All @@ -121,6 +131,40 @@ private function setDefaults(string $key, Parameter $parameter, string $resource
}
}

if (!$parameter->getConstraint()) {
$parameter = $this->addSchemaValidation($schema);
}

//  ArrayItems.php
//  Enum.php
//  Length.php
//  MultipleOf.php
//  Pattern.php
//  Required.php

return $parameter;
}

private function addSchemaValidation(Parameter $parameter)
{
$assertions = [];

if (isset($schema['exclusiveMinimum'])) {
$assertions[] = new GreaterThan(value: $schema['exclusiveMinimum'], propertyPath: $parameter->getProperty() ?? $parameter->getKey());
}

if (isset($schema['exclusiveMaximum'])) {
$assertions[] = new LessThan(value: $schema['exclusiveMaximum'], propertyPath: $parameter->getProperty() ?? $parameter->getKey());
}

if (isset($schema['minimum'])) {
$assertions[] = new GreaterThanOrEqual(value: $schema['minimum'], propertyPath: $parameter->getProperty() ?? $parameter->getKey());
}

if (isset($schema['maximum'])) {
$assertions[] = new LessThanOrEqual(value: $schema['maximum'], propertyPath: $parameter->getProperty() ?? $parameter->getKey());
}


}
}
1 change: 1 addition & 0 deletions src/Metadata/Tests/Fixtures/ApiResource/WithParameter.php
Expand Up @@ -17,6 +17,7 @@
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\HeaderParameter;
use ApiPlatform\Metadata\QueryParameter;
use Symfony\Component\Validator\Constraints\Required;

#[ApiResource(
parameters: [
Expand Down
1 change: 1 addition & 0 deletions src/State/Provider/ParameterProvider.php
Expand Up @@ -57,6 +57,7 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
$key = $parameter->getKey();
$parameters = $this->extractParameterValues($parameter, $request, $context);
$parsedKey = explode('[:property]', $key);

if (isset($parsedKey[0]) && isset($parameters[$parsedKey[0]])) {
$key = $parsedKey[0];
}
Expand Down
Expand Up @@ -818,6 +818,7 @@ private function registerValidatorConfiguration(ContainerBuilder $container, arr
if (interface_exists(ValidatorInterface::class)) {
$loader->load('metadata/validator.xml');
$loader->load('validator/validator.xml');
$loader->load('symfony/parameter_validator.xml');

if ($this->isConfigEnabled($container, $config['graphql'])) {
$loader->load('graphql/validator.xml');
Expand Down Expand Up @@ -845,6 +846,7 @@ private function registerValidatorConfiguration(ContainerBuilder $container, arr
if (!$config['validator']['query_parameter_validation']) {
$container->removeDefinition('api_platform.listener.view.validate_query_parameters');
$container->removeDefinition('api_platform.validator.query_parameter_validator');
$container->removeDefinition('api_platform.symfony.parameter_validator');
}
}

Expand Down
@@ -0,0 +1,11 @@
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="api_platform.symfony.parameter_validator" class="ApiPlatform\Symfony\Validator\State\ParameterValidatorProvider" public="true" decorates="api_platform.state_provider.parameter">
<argument type="service" id="api_platform.symfony.parameter_validator.inner" />
<argument type="service" id="validator" />
</service>
</services>
</container>
79 changes: 79 additions & 0 deletions src/Symfony/Validator/State/ParameterValidatorProvider.php
@@ -0,0 +1,79 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Symfony\Validator\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use ApiPlatform\Validator\Exception\ValidationException;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
* Validates parameters using the symfony validator
*
* @experimental
*/
final class ParameterValidatorProvider implements ProviderInterface
{
public function __construct(
private readonly ProviderInterface $decorated,
private readonly ValidatorInterface $validator
) {
}

public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
$body = $this->decorated->provide($operation, $uriVariables, $context);
if (!$context['request'] ?? null) {
return $body;
}

$operation = $context['request']->attributes->get('_api_operation');
foreach ($operation->getParameters() as $parameter) {
if (!$constraints = $parameter->getConstraint()) {
continue;
}

// This is computed in @see ApiPlatform\State\Provider\ParameterProvider
if (!\array_key_exists('_api_values', $parameter->getExtraProperties())) {
continue;
}

$violations = $this->validator->validate(current($parameter->getExtraProperties()['_api_values']), $constraints);

if (0 !== \count($violations)) {
$constraintViolationList = new ConstraintViolationList();
foreach ($violations as $violation) {
$constraintViolationList->add(new ConstraintViolation(
$violation->getMessage(),
$violation->getMessageTemplate(),
$violation->getParameters(),
$violation->getRoot(),
$parameter->getProperty() ?? $parameter->getKey(),
$violation->getInvalidValue(),
$violation->getPlural(),
$violation->getCode(),
$violation->getConstraint(),
$violation->getCause()
));
}

throw new ValidationException($constraintViolationList);
}
}

return $body;
}
}
5 changes: 3 additions & 2 deletions tests/Fixtures/TestBundle/ApiResource/WithParameter.php
Expand Up @@ -23,6 +23,7 @@
use ApiPlatform\Tests\Fixtures\TestBundle\Parameter\CustomGroupParameterProvider;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Validator\Constraints\NotBlank;

#[Get(
uriTemplate: 'with_parameters/{id}{._format}',
Expand All @@ -42,9 +43,9 @@
provider: [self::class, 'provide']
)]
#[GetCollection(
uriTemplate: 'with_parameters_collection',
uriTemplate: 'with_parameters_collection{._format}',
parameters: [
'hydra' => new QueryParameter(property: 'a', required: true),
'hydra' => new QueryParameter(property: 'a', required: true, constraint: new NotBlank()),
],
provider: [self::class, 'collectionProvider']
)]
Expand Down
15 changes: 15 additions & 0 deletions tests/Functional/Parameters/ValidationTests.php
@@ -0,0 +1,15 @@
<?php

namespace ApiPlatform\Tests\Functional\Parameters;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;

final class ValidationTests extends ApiTestCase
{
public function testWithGroupFilter(): void
{
$response = self::createClient()->request('GET', 'with_parameters_collection?hydra=');
$this->assertArraySubset(['violations' => [['propertyPath' => 'a', 'message' => 'This value should not be blank.']]], $response->toArray(false));
}

}

0 comments on commit 1f573d0

Please sign in to comment.