Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Serializer] Fix ignored callbacks in denormalization #45323

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

Merged
merged 1 commit into from
Feb 11, 2022
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.
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 @@ -79,15 +79,15 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
public const DEFAULT_CONSTRUCTOR_ARGUMENTS = 'default_constructor_arguments';

/**
* Hashmap of field name => callable to normalize this field.
* Hashmap of field name => callable to (de)normalize this field.
*
* The callable is called if the field is encountered with the arguments:
*
* - mixed $attributeValue value of this field
* - object $object the whole object being normalized
* - string $attributeName name of the attribute being normalized
* - string $format the requested format
* - array $context the serialization context
* - mixed $attributeValue value of this field
* - object|string $object the whole object being normalized or the object's class being denormalized
* - string $attributeName name of the attribute being (de)normalized
* - string $format the requested format
* - array $context the serialization context
*/
public const CALLBACKS = 'callbacks';

Expand Down Expand Up @@ -168,17 +168,7 @@ public function __construct(ClassMetadataFactoryInterface $classMetadataFactory
$this->nameConverter = $nameConverter;
$this->defaultContext = array_merge($this->defaultContext, $defaultContext);

if (isset($this->defaultContext[self::CALLBACKS])) {
if (!\is_array($this->defaultContext[self::CALLBACKS])) {
throw new InvalidArgumentException(sprintf('The "%s" default context option must be an array of callables.', self::CALLBACKS));
}

foreach ($this->defaultContext[self::CALLBACKS] as $attribute => $callback) {
if (!\is_callable($callback)) {
throw new InvalidArgumentException(sprintf('Invalid callback found for attribute "%s" in the "%s" default context option.', $attribute, self::CALLBACKS));
}
}
}
$this->validateCallbackContext($this->defaultContext, 'default');

if (isset($this->defaultContext[self::CIRCULAR_REFERENCE_HANDLER]) && !\is_callable($this->defaultContext[self::CIRCULAR_REFERENCE_HANDLER])) {
throw new InvalidArgumentException(sprintf('Invalid callback found in the "%s" default context option.', self::CIRCULAR_REFERENCE_HANDLER));
Expand Down Expand Up @@ -220,11 +210,11 @@ public function setCircularReferenceHandler(callable $circularReferenceHandler)
}

/**
* Sets normalization callbacks.
* Sets (de)normalization callbacks.
*
* @deprecated since Symfony 4.2
*
* @param callable[] $callbacks Help normalize the result
* @param callable[] $callbacks Help (de)normalize the result
*
* @return self
*
Expand Down Expand Up @@ -532,7 +522,7 @@ protected function denormalizeParameter(\ReflectionClass $class, \ReflectionPara
throw new LogicException(sprintf('Cannot create an instance of "%s" from serialized data because the serializer inject in "%s" is not a denormalizer.', $parameterClass, static::class));
}

return $this->serializer->denormalize($parameterData, $parameterClass, $format, $this->createChildContext($context, $parameterName, $format));
$parameterData = $this->serializer->denormalize($parameterData, $parameterClass, $format, $this->createChildContext($context, $parameterName, $format));
}
} catch (\ReflectionException $e) {
throw new RuntimeException(sprintf('Could not determine the class of the parameter "%s".', $parameterName), 0, $e);
Expand All @@ -544,7 +534,7 @@ protected function denormalizeParameter(\ReflectionClass $class, \ReflectionPara
return null;
}

return $parameterData;
return $this->applyCallbacks($parameterData, $class->getName(), $parameterName, $format, $context);
}

/**
Expand All @@ -565,4 +555,46 @@ protected function createChildContext(array $parentContext, $attribute/*, ?strin

return $parentContext;
}

/**
* Validate callbacks set in context.
*
* @param string $contextType Used to specify which context is invalid in exceptions
*
* @throws InvalidArgumentException
*/
final protected function validateCallbackContext(array $context, string $contextType = ''): void
{
if (!isset($context[self::CALLBACKS])) {
return;
}

if (!\is_array($context[self::CALLBACKS])) {
throw new InvalidArgumentException(sprintf('The "%s"%s context option must be an array of callables.', self::CALLBACKS, '' !== $contextType ? " $contextType" : ''));
}

foreach ($context[self::CALLBACKS] as $attribute => $callback) {
if (!\is_callable($callback)) {
throw new InvalidArgumentException(sprintf('Invalid callback found for attribute "%s" in the "%s"%s context option.', $attribute, self::CALLBACKS, '' !== $contextType ? " $contextType" : ''));
}
}
}

/**
* Apply callbacks set in context.
*
* @param mixed $value
* @param object|string $object Can be either the object being normalizing or the object's class being denormalized
*
* @return mixed
*/
final protected function applyCallbacks($value, $object, string $attribute, ?string $format, array $context)
{
/**
* @var callable|null
*/
$callback = $context[self::CALLBACKS][$attribute] ?? $this->defaultContext[self::CALLBACKS][$attribute] ?? $this->callbacks[$attribute] ?? null;

return $callback ? $callback($value, $object, $attribute, $format, $context) : $value;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -145,17 +145,7 @@ public function normalize($object, $format = null, array $context = [])
$context['cache_key'] = $this->getCacheKey($format, $context);
}

if (isset($context[self::CALLBACKS])) {
if (!\is_array($context[self::CALLBACKS])) {
throw new InvalidArgumentException(sprintf('The "%s" context option must be an array of callables.', self::CALLBACKS));
}

foreach ($context[self::CALLBACKS] as $attribute => $callback) {
if (!\is_callable($callback)) {
throw new InvalidArgumentException(sprintf('Invalid callback found for attribute "%s" in the "%s" context option.', $attribute, self::CALLBACKS));
}
}
}
$this->validateCallbackContext($context);

if ($this->isCircularReference($object, $context)) {
return $this->handleCircularReference($object, $format, $context);
Expand Down Expand Up @@ -203,13 +193,7 @@ public function normalize($object, $format = null, array $context = [])
$attributeValue = $maxDepthHandler($attributeValue, $object, $attribute, $format, $context);
}

/**
* @var callable|null
*/
$callback = $context[self::CALLBACKS][$attribute] ?? $this->defaultContext[self::CALLBACKS][$attribute] ?? $this->callbacks[$attribute] ?? null;
if ($callback) {
$attributeValue = $callback($attributeValue, $object, $attribute, $format, $context);
}
$attributeValue = $this->applyCallbacks($attributeValue, $object, $attribute, $format, $context);

if (null !== $attributeValue && !is_scalar($attributeValue)) {
$stack[$attribute] = $attributeValue;
Expand Down Expand Up @@ -346,6 +330,8 @@ public function denormalize($data, $type, $format = null, array $context = [])
$context['cache_key'] = $this->getCacheKey($format, $context);
}

$this->validateCallbackContext($context);

$allowedAttributes = $this->getAllowedAttributes($type, $context, true);
$normalizedData = $this->prepareForDenormalization($data);
$extraAttributes = [];
Expand Down Expand Up @@ -375,6 +361,8 @@ public function denormalize($data, $type, $format = null, array $context = [])
}

$value = $this->validateAndDenormalize($resolvedClass, $attribute, $value, $format, $context);
$value = $this->applyCallbacks($value, $resolvedClass, $attribute, $format, $context);

try {
$this->setAttributeValue($object, $attribute, $value, $format, $context);
} catch (InvalidArgumentException $e) {
Expand Down Expand Up @@ -509,7 +497,9 @@ protected function denormalizeParameter(\ReflectionClass $class, \ReflectionPara
return parent::denormalizeParameter($class, $parameter, $parameterName, $parameterData, $context, $format);
}

return $this->validateAndDenormalize($class->getName(), $parameterName, $parameterData, $format, $context);
$parameterData = $this->validateAndDenormalize($class->getName(), $parameterName, $parameterData, $format, $context);

return $this->applyCallbacks($parameterData, $class->getName(), $parameterName, $format, $context);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,34 @@ class CallbacksObject
{
public $bar;

public function __construct($bar = null)
/**
* @var string|null
*/
public $foo;

public function __construct($bar = null, string $foo = null)
{
$this->bar = $bar;
$this->foo = $foo;
}

public function getBar()
{
return $this->bar;
}

public function setBar($bar)
{
$this->bar = $bar;
}

public function getFoo(): ?string
{
return $this->foo;
}

public function setFoo(?string $foo)
{
$this->foo = $foo;
}
}
Loading