Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions features/filter/filter_validation.feature
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ Feature: Validate filters based upon filter description
Scenario: Required filter should throw an error if not set
When I am on "/array_filter_validators"
Then the response status code should be 422
And the JSON node "detail" should be equal to 'arrayRequired: This value should not be blank.\nindexedArrayRequired: This value should not be blank.'
And the JSON node "detail" should be equal to 'arrayRequired[]: This value should not be blank.\nindexedArrayRequired[foo]: This value should not be blank.'

When I am on "/array_filter_validators?arrayRequired[foo]=foo"
Then the response status code should be 422
And the JSON node "detail" should be equal to 'indexedArrayRequired: This value should not be blank.'
And the JSON node "detail" should be equal to 'indexedArrayRequired[foo]: This value should not be blank.'

When I am on "/array_filter_validators?arrayRequired[]=foo"
Then the response status code should be 422
And the JSON node "detail" should be equal to 'indexedArrayRequired: This value should not be blank.'
And the JSON node "detail" should be equal to 'indexedArrayRequired[foo]: This value should not be blank.'

Scenario: Test filter bounds: maximum
When I am on "/filter_validators?required=foo&required-allow-empty&maximum=10"
Expand All @@ -49,7 +49,7 @@ Feature: Validate filters based upon filter description

When I am on "/filter_validators?required=foo&required-allow-empty&exclusiveMaximum=10"
Then the response status code should be 422
And the JSON node "detail" should be equal to 'maximum: This value should be less than 10.'
And the JSON node "detail" should be equal to 'exclusiveMaximum: This value should be less than 10.'

Scenario: Test filter bounds: minimum
When I am on "/filter_validators?required=foo&required-allow-empty&minimum=5"
Expand Down
4 changes: 2 additions & 2 deletions src/Metadata/Parameter.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,9 @@ public function getSecurityMessage(): ?string
*
* @readonly
*/
public function getValue(): mixed
public function getValue(mixed $default = new ParameterNotFound()): mixed
{
return $this->extraProperties['_api_values'] ?? new ParameterNotFound();
return $this->extraProperties['_api_values'] ?? $default;
}

/**
Expand Down
6 changes: 3 additions & 3 deletions src/Metadata/Parameters.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function add(string $key, Parameter $value): self
/**
* @param class-string $parameterClass
*/
public function remove(string $key, string $parameterClass): self
public function remove(string $key, string $parameterClass = QueryParameter::class): self
{
foreach ($this->parameters as $i => [$parameterName, $parameter]) {
if ($parameterName === $key && $parameterClass === $parameter::class) {
Expand All @@ -86,7 +86,7 @@ public function remove(string $key, string $parameterClass): self
/**
* @param class-string $parameterClass
*/
public function get(string $key, string $parameterClass): ?Parameter
public function get(string $key, string $parameterClass = QueryParameter::class): ?Parameter
{
foreach ($this->parameters as [$parameterName, $parameter]) {
if ($parameterName === $key && $parameterClass === $parameter::class) {
Expand All @@ -100,7 +100,7 @@ public function get(string $key, string $parameterClass): ?Parameter
/**
* @param class-string $parameterClass
*/
public function has(string $key, string $parameterClass): bool
public function has(string $key, string $parameterClass = QueryParameter::class): bool
{
foreach ($this->parameters as [$parameterName, $parameter]) {
if ($parameterName === $key && $parameterClass === $parameter::class) {
Expand Down
28 changes: 28 additions & 0 deletions src/Metadata/Tests/ParameterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?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\Metadata\Tests;

use ApiPlatform\Metadata\QueryParameter;
use ApiPlatform\State\ParameterNotFound;
use PHPUnit\Framework\TestCase;

class ParameterTest extends TestCase
{
public function testDefaultValue(): void
{
$parameter = new QueryParameter();
$this->assertSame('test', $parameter->getValue('test'));
$this->assertInstanceOf(ParameterNotFound::class, $parameter->getValue());
}
}
28 changes: 28 additions & 0 deletions src/Metadata/Tests/ParametersTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?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\Metadata\Tests;

use ApiPlatform\Metadata\Parameters;
use ApiPlatform\Metadata\QueryParameter;
use PHPUnit\Framework\TestCase;

class ParametersTest extends TestCase
{
public function testDefaultValue(): void
{
$r = new QueryParameter();
$parameters = new Parameters(['a' => $r]);
$this->assertSame($r, $parameters->get('a'));
}
}
27 changes: 23 additions & 4 deletions src/Symfony/Validator/State/ParameterValidatorProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@
namespace ApiPlatform\Symfony\Validator\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Parameter;
use ApiPlatform\State\ParameterNotFound;
use ApiPlatform\State\ProviderInterface;
use ApiPlatform\State\Util\ParameterParserTrait;
use ApiPlatform\Validator\Exception\ValidationException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Validator\ValidatorInterface;

Expand Down Expand Up @@ -55,7 +57,6 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
continue;
}

$key = $parameter->getKey();
$value = $parameter->getValue();
if ($value instanceof ParameterNotFound) {
$value = null;
Expand All @@ -68,9 +69,7 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
$violation->getMessageTemplate(),
$violation->getParameters(),
$violation->getRoot(),
$parameter->getProperty() ?? (
str_contains($key, ':property') ? str_replace('[:property]', $violation->getPropertyPath(), $key) : $key.$violation->getPropertyPath()
),
$this->getProperty($parameter, $violation),
$violation->getInvalidValue(),
$violation->getPlural(),
$violation->getCode(),
Expand All @@ -86,4 +85,24 @@ public function provide(Operation $operation, array $uriVariables = [], array $c

return $this->decorated->provide($operation, $uriVariables, $context);
}

// There's a `property` inside Parameter but it's used for hydra:search only as here we want the parameter name instead
private function getProperty(Parameter $parameter, ConstraintViolationInterface $violation): string
{
$key = $parameter->getKey();

if (str_contains($key, '[:property]')) {
return str_replace('[:property]', $violation->getPropertyPath(), $key);
}

if (str_contains($key, ':property')) {
return str_replace(':property', $violation->getPropertyPath(), $key);
}

if ($p = $violation->getPropertyPath()) {
return $p;
}

return $key;
}
}
22 changes: 22 additions & 0 deletions tests/Fixtures/TestBundle/ApiResource/WithParameter.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Validator\Constraints as Assert;

#[Get(
uriTemplate: 'with_parameters/{id}{._format}',
Expand Down Expand Up @@ -63,6 +64,7 @@
'array' => new QueryParameter(schema: ['minItems' => 2, 'maxItems' => 3]),
'multipleOf' => new QueryParameter(schema: ['multipleOf' => 2]),
'pattern' => new QueryParameter(schema: ['pattern' => '/\d/']),
'int' => new QueryParameter(property: 'a', constraints: [new Assert\Type('integer')], provider: [self::class, 'toInt']),
],
provider: [self::class, 'collectionProvider']
)]
Expand Down Expand Up @@ -132,4 +134,24 @@ public static function headerAndQueryProvider(Operation $operation, array $uriVa

return new JsonResponse($values);
}

public static function toInt(Parameter $parameter, array $parameters = [], array $context = []): ?Operation
{
if (null === ($operation = $context['operation'] ?? null)) {
return null;
}

$value = $parameter->getValue();

if (is_numeric($value)) {
$value = (int) $value;
}

$parameters = $operation->getParameters();
$parameters->add($parameter->getKey(), $parameter = $parameter->withExtraProperties(
$parameter->getExtraProperties() + ['_api_values' => $value]
));

return $operation->withParameters($parameters);
}
}
10 changes: 9 additions & 1 deletion tests/Functional/Parameters/ValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ final class ValidationTest extends ApiTestCase
public function testWithGroupFilter(): void
{
$response = self::createClient()->request('GET', 'with_parameters_collection');
$this->assertArraySubset(['violations' => [['propertyPath' => 'a', 'message' => 'The parameter "hydra" is required.']]], $response->toArray(false));
$this->assertArraySubset(['violations' => [['message' => 'The parameter "hydra" is required.']]], $response->toArray(false));
$response = self::createClient()->request('GET', 'with_parameters_collection?hydra');
$this->assertResponseIsSuccessful();
}
Expand Down Expand Up @@ -134,4 +134,12 @@ public function testValidatePropertyPlaceholder(): void
],
], $response->toArray(false));
}

public function testValidateMessage(): void
{
$response = self::createClient()->request('GET', 'validate_parameters?int=test');
$this->assertArraySubset([
'detail' => 'int: This value should be of type integer.',
], $response->toArray(false));
}
}
Loading