Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Serializer] Provide context information from attribute for promoted properties #46680

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
Jul 3, 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 @@ -334,7 +334,8 @@ protected function instantiateObject(array &$data, string $class, array &$contex
$params = [];
foreach ($constructorParameters as $constructorParameter) {
$paramName = $constructorParameter->name;
$key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
$attributeContext = $this->getAttributeDenormalizationContext($class, $paramName, $context);
$key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $attributeContext) : $paramName;

$allowed = false === $allowedAttributes || \in_array($paramName, $allowedAttributes);
$ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
Expand All @@ -346,7 +347,7 @@ protected function instantiateObject(array &$data, string $class, array &$contex

$variadicParameters = [];
foreach ($data[$paramName] as $parameterData) {
$variadicParameters[] = $this->denormalizeParameter($reflectionClass, $constructorParameter, $paramName, $parameterData, $context, $format);
$variadicParameters[] = $this->denormalizeParameter($reflectionClass, $constructorParameter, $paramName, $parameterData, $attributeContext, $format);
}

$params = array_merge($params, $variadicParameters);
Expand All @@ -363,7 +364,7 @@ protected function instantiateObject(array &$data, string $class, array &$contex

// Don't run set for a parameter passed to the constructor
try {
$params[] = $this->denormalizeParameter($reflectionClass, $constructorParameter, $paramName, $parameterData, $context, $format);
$params[] = $this->denormalizeParameter($reflectionClass, $constructorParameter, $paramName, $parameterData, $attributeContext, $format);
} catch (NotNormalizableValueException $exception) {
if (!isset($context['not_normalizable_value_exceptions'])) {
throw $exception;
Expand Down Expand Up @@ -485,4 +486,43 @@ final protected function applyCallbacks(mixed $value, object|string $object, str

return $callback ? $callback($value, $object, $attribute, $format, $context) : $value;
}

/**
* Computes the normalization context merged with current one. Metadata always wins over global context, as more specific.
*
* @internal
*/
protected function getAttributeNormalizationContext(object $object, string $attribute, array $context): array
ogizanagi marked this conversation as resolved.
Show resolved Hide resolved
{
if (null === $metadata = $this->getAttributeMetadata($object, $attribute)) {
return $context;
}

return array_merge($context, $metadata->getNormalizationContextForGroups($this->getGroups($context)));
}

/**
* Computes the denormalization context merged with current one. Metadata always wins over global context, as more specific.
*
* @internal
*/
protected function getAttributeDenormalizationContext(string $class, string $attribute, array $context): array
{
$context['deserialization_path'] = ($context['deserialization_path'] ?? false) ? $context['deserialization_path'].'.'.$attribute : $attribute;

if (null === $metadata = $this->getAttributeMetadata($class, $attribute)) {
return $context;
}

return array_merge($context, $metadata->getDenormalizationContextForGroups($this->getGroups($context)));
}

private function getAttributeMetadata($objectOrClass, string $attribute): ?AttributeMetadataInterface
{
if (!$this->classMetadataFactory) {
return null;
}

return $this->classMetadataFactory->getMetadataFor($objectOrClass)->getAttributesMetadata()[$attribute] ?? null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?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\Tests\Fixtures\Annotations;

use Symfony\Component\Serializer\Annotation\Context;

/**
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
class ContextDummyPromotedProperties extends ContextDummyParent
{
public function __construct(
/**
* @Context({ "foo" = "value", "bar" = "value", "nested" = {
* "nested_key" = "nested_value",
* }, "array": { "first", "second" } })
* @Context({ "bar" = "value_for_group_a" }, groups = "a")
*/
public $foo,

/**
* @Context(
* normalizationContext = { "format" = "d/m/Y" },
* denormalizationContext = { "format" = "m-d-Y H:i" },
* groups = {"a", "b"}
* )
*/
public $bar,

/**
* @Context(normalizationContext={ "prop" = "dummy_value" })
*/
public $overriddenParentProperty,
) {
}

/**
* @Context({ "method" = "method_with_context" })
*/
public function getMethodWithContext()
{
return 'method_with_context';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?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\Tests\Fixtures\Attributes;

use Symfony\Component\Serializer\Annotation\Context;

/**
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
class ContextDummyPromotedProperties extends ContextDummyParent
{
public function __construct(
#[Context(['foo' => 'value', 'bar' => 'value', 'nested' => [
'nested_key' => 'nested_value',
], 'array' => ['first', 'second']])]
#[Context(context: ['bar' => 'value_for_group_a'], groups: ['a'])]
public $foo,

#[Context(
normalizationContext: ['format' => 'd/m/Y'],
denormalizationContext: ['format' => 'm-d-Y H:i'],
groups: ['a', 'b'],
)]
public $bar,

#[Context(normalizationContext: ['prop' => 'dummy_value'])]
public $overriddenParentProperty,
) {
}

#[Context(['method' => 'method_with_context'])]
public function getMethodWithContext()
{
return 'method_with_context';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,14 @@ public function testLoadContexts()
$this->assertLoadedContexts($this->getNamespace().'\ContextDummy', $this->getNamespace().'\ContextDummyParent');
}

/**
* @requires PHP 8
Copy link
Contributor

Choose a reason for hiding this comment

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

This @requires won't be necessary if we merge this to 6.2

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Feel free to merge it either in 4.4 (as i saw this is latest maintained version) or 6.2. Or do you need me to update this here?

Copy link
Contributor

Choose a reason for hiding this comment

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

The attribute is not available in 4.4 yet.
Since @dunglas seems to agree with me this should be considered a new feature, as of PHP 8 specific feature, we'll merge it to 6.2. The rebase and changing this line is not necessary, we can do it while merging, but updating the PR to the right branch might be helpful to detect unexpected issues on the CI.

*/
public function testLoadContextsPropertiesPromoted()
{
$this->assertLoadedContexts($this->getNamespace().'\ContextDummyPromotedProperties', $this->getNamespace().'\ContextDummyParent');
}

public function testThrowsOnContextOnInvalidMethod()
{
$class = $this->getNamespace().'\BadMethodContextDummy';
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.