Skip to content

[Serializer] Improve nested payload validation for #[MapRequestPayload] using a new serialization context #53250

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: 7.4
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\PropertyAccess\Exception\InvalidTypeException;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
Expand Down Expand Up @@ -285,6 +284,69 @@ public function testValidationNotPerformedWhenPartialDenormalizationReturnsViola
}
}

public function testNestedPayloadErrorReportingWhenPartialDenormalizationReturnsViolation()
{
$content = '{
"name": "john doe",
"address": {
"address": "2332 street",
"zipcode": "20220",
"city": "Paris",
"country": "75000",
"geolocalization": {
"lng": 32.423
}
}
}';
$serializer = new Serializer([new ObjectNormalizer()], ['json' => new JsonEncoder()]);

$validator = $this->createMock(ValidatorInterface::class);
$validator->expects($this->never())
->method('validate');

$resolver = new RequestPayloadValueResolver($serializer, $validator);
$request = Request::create('/', 'POST', server: ['CONTENT_TYPE' => 'application/json'], content: $content);
$kernel = $this->createMock(HttpKernelInterface::class);

// Test using use_class_as_default_expected_type = false context
$argument = new ArgumentMetadata('invalid-nested-payload', Employee::class, false, false, null, false, [
MapRequestPayload::class => new MapRequestPayload(serializationContext: ['use_class_as_default_expected_type' => false]),
]);
$arguments = $resolver->resolve($request, $argument);
$event = new ControllerArgumentsEvent($kernel, function () {}, $arguments, $request, HttpKernelInterface::MAIN_REQUEST);

try {
$resolver->onKernelControllerArguments($event);
$this->fail(sprintf('Expected "%s" to be thrown.', HttpException::class));
} catch (HttpException $e) {
$validationFailedException = $e->getPrevious();
$this->assertInstanceOf(ValidationFailedException::class, $validationFailedException);
$this->assertSame(
sprintf('This value should be of type %s.', 'unknown'),
$validationFailedException->getViolations()[0]->getMessage()
);
}

// Test using use_class_as_default_expected_type context
$argument = new ArgumentMetadata('invalid-nested-payload', Employee::class, false, false, null, false, [
MapRequestPayload::class => new MapRequestPayload(serializationContext: ['use_class_as_default_expected_type' => true]),
]);
$arguments = $resolver->resolve($request, $argument);
$event = new ControllerArgumentsEvent($kernel, function () {}, $arguments, $request, HttpKernelInterface::MAIN_REQUEST);

try {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can leverage expectException and expectExceptionMessage instead

$resolver->onKernelControllerArguments($event);
$this->fail(sprintf('Expected "%s" to be thrown.', HttpException::class));
} catch (HttpException $e) {
$validationFailedException = $e->getPrevious();
$this->assertInstanceOf(ValidationFailedException::class, $validationFailedException);
$this->assertSame(
sprintf('This value should be of type %s.', Geolocalization::class),
$validationFailedException->getViolations()[0]->getMessage()
);
}
}

public function testUnsupportedMedia()
{
$serializer = new Serializer();
Expand Down Expand Up @@ -731,3 +793,34 @@ public function getPassword(): string
return $this->password;
}
}

class Employee
{
public function __construct(
public string $name,
#[Assert\Valid]
public ?Address $address = null,
) {
}
}

class Address
{
public function __construct(
public string $address,
public string $zipcode,
public string $city,
public string $country,
public Geolocalization $geolocalization,
) {
}
}

class Geolocalization
{
public function __construct(
public string $lat,
public string $lng,
) {
}
}
4 changes: 4 additions & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
CHANGELOG
=========

7.1
---
* Add `AbstractNormalizer::USE_CLASS_AS_DEFAULT_EXPECTED_TYPE` in order to use the FQCN as the default value for NotNormalizableValueException's expectedTypes instead of unknown

7.0
---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,11 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
*/
public const REQUIRE_ALL_PROPERTIES = 'require_all_properties';

/**
* Use class name as default expected type when throwing NotNormalizableValueException instead of unknown.
*/
public const USE_CLASS_AS_DEFAULT_EXPECTED_TYPE = 'use_class_as_default_expected_type';

/**
* @internal
*/
Expand Down Expand Up @@ -380,7 +385,7 @@ protected function instantiateObject(array &$data, string $class, array &$contex
$exception = NotNormalizableValueException::createForUnexpectedDataType(
sprintf('Failed to create object because the class misses the "%s" property.', $constructorParameter->name),
$data,
['unknown'],
[isset($context[self::USE_CLASS_AS_DEFAULT_EXPECTED_TYPE]) && $context[self::USE_CLASS_AS_DEFAULT_EXPECTED_TYPE] ? $class : 'unknown'],
$context['deserialization_path'] ?? null,
true
);
Expand Down Expand Up @@ -424,12 +429,7 @@ protected function instantiateObject(array &$data, string $class, array &$contex
unset($context['has_constructor']);

if (!$reflectionClass->isInstantiable()) {
throw NotNormalizableValueException::createForUnexpectedDataType(
sprintf('Failed to create object because the class "%s" is not instantiable.', $class),
$data,
['unknown'],
$context['deserialization_path'] ?? null
);
throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('Failed to create object because the class "%s" is not instantiable.', $class), $data, ['unknown'], $context['deserialization_path'] ?? null);
}

return new $class();
Expand Down