Skip to content
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

[Serializer] Add context for CamelCaseToSnakeCaseNameConverter #53898

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -24,6 +24,7 @@
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
use Symfony\Component\Serializer\Exception\UnexpectedPropertyException;
use Symfony\Component\Serializer\Exception\UnsupportedFormatException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\SerializerInterface;
Expand Down Expand Up @@ -197,6 +198,8 @@ private function mapRequestPayload(Request $request, string $type, MapRequestPay
throw new UnsupportedMediaTypeHttpException(sprintf('Unsupported format: "%s".', $format), $e);
} catch (NotEncodableValueException $e) {
throw new BadRequestHttpException(sprintf('Request payload contains invalid "%s" data.', $format), $e);
} catch (UnexpectedPropertyException $e) {
throw new BadRequestHttpException(sprintf('Request payload contains invalid "%s" property.', $e->property), $e);
}
}
}
@@ -0,0 +1,29 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Exception;

/**
* UnexpectedPropertyException.
*
* @author Aurélien Pillevesse <aurelienpillevesse@hotmail.fr>
*/
class UnexpectedPropertyException extends \UnexpectedValueException implements ExceptionInterface
{
public function __construct(
public readonly string $property,
?\Throwable $previous = null,
) {
$msg = sprintf('Property is not allowed ("%s" is unknown).', $this->property);

parent::__construct($msg, 0, $previous);
}
}
Expand Up @@ -11,13 +11,21 @@

namespace Symfony\Component\Serializer\NameConverter;

use Symfony\Component\Serializer\Exception\UnexpectedPropertyException;

/**
* CamelCase to Underscore name converter.
*
* @author Kévin Dunglas <dunglas@gmail.com>
* @author Aurélien Pillevesse <aurelienpillevesse@hotmail.fr>
*/
class CamelCaseToSnakeCaseNameConverter implements NameConverterInterface
class CamelCaseToSnakeCaseNameConverter implements AdvancedNameConverterInterface
{
/**
* Require all properties to be written in snake_case.
*/
public const REQUIRE_SNAKE_CASE_PROPERTIES = 'require_snake_case_properties';

/**
* @param array|null $attributes The list of attributes to rename or null for all attributes
* @param bool $lowerCamelCase Use lowerCamelCase style
Expand All @@ -28,7 +36,7 @@ public function __construct(
) {
}

public function normalize(string $propertyName): string
public function normalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string
{
if (null === $this->attributes || \in_array($propertyName, $this->attributes, true)) {
return strtolower(preg_replace('/[A-Z]/', '_\\0', lcfirst($propertyName)));
Expand All @@ -37,8 +45,12 @@ public function normalize(string $propertyName): string
return $propertyName;
}

public function denormalize(string $propertyName): string
public function denormalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string
{
if (($context[self::REQUIRE_SNAKE_CASE_PROPERTIES] ?? false) && $propertyName !== $this->normalize($propertyName, $class, $format, $context)) {
throw new UnexpectedPropertyException($propertyName);
}

$camelCasedName = preg_replace_callback('/(^|_|\.)+(.)/', fn ($match) => ('.' === $match[1] ? '_' : '').strtoupper($match[2]), $propertyName);

if ($this->lowerCamelCase) {
Expand Down
Expand Up @@ -12,11 +12,13 @@
namespace Symfony\Component\Serializer\Tests\NameConverter;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Exception\UnexpectedPropertyException;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

/**
* @author Kévin Dunglas <dunglas@gmail.com>
* @author Aurélien Pillevesse <aurelienpillevesse@hotmail.fr>
*/
class CamelCaseToSnakeCaseNameConverterTest extends TestCase
{
Expand Down Expand Up @@ -55,4 +57,20 @@ public static function attributeProvider()
['this_is_a_test', 'ThisIsATest', false],
];
}

public function testDenormalizeWithContext()
{
$nameConverter = new CamelCaseToSnakeCaseNameConverter(null, true);
$denormalizedValue = $nameConverter->denormalize('last_name', context: [CamelCaseToSnakeCaseNameConverter::REQUIRE_SNAKE_CASE_PROPERTIES]);

$this->assertSame($denormalizedValue, 'lastName');
}

public function testErrorDenormalizeWithContext()
{
$nameConverter = new CamelCaseToSnakeCaseNameConverter(null, true);

$this->expectException(UnexpectedPropertyException::class);
$nameConverter->denormalize('lastName', context: [CamelCaseToSnakeCaseNameConverter::REQUIRE_SNAKE_CASE_PROPERTIES => true]);
}
}