-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
[Serializer] Add a NormalizerDumper #22051
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
Changes from all commits
5fe5737
32abf6c
6c4f6be
47adb72
133766f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
use Symfony\Bundle\FrameworkBundle\FrameworkBundle; | ||
|
||
return array( | ||
new FrameworkBundle(), | ||
); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
imports: | ||
- { resource: ../config/default.yml } | ||
|
||
framework: | ||
serializer: | ||
enable_normalizer_generation: true | ||
enable_annotations: true # required to detect properties |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,211 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\Serializer\Dumper; | ||
|
||
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; | ||
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; | ||
use Symfony\Component\Serializer\NormalizerInterface; | ||
|
||
/** | ||
* @author Guilhem Niot <[email protected]> | ||
* @author Amrouche Hamza <[email protected]> | ||
* | ||
* @experimental | ||
*/ | ||
final class NormalizerDumper | ||
{ | ||
private $classMetadataFactory; | ||
|
||
public function __construct(ClassMetadataFactoryInterface $classMetadataFactory) | ||
{ | ||
$this->classMetadataFactory = $classMetadataFactory; | ||
} | ||
|
||
public function dump(string $class, array $context = array()) | ||
{ | ||
$reflectionClass = new \ReflectionClass($class); | ||
if (!isset($context['class'])) { | ||
$context['class'] = $reflectionClass->getShortName().'Normalizer'; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I really think we should introduce a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think the namespace option is enough (maybe we should use it by default though). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hmm, yes in fact I saw this option while working with it but I didn't try it. I'll, and yes I think we should make it default. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Rethinking about it, I think we should make the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes that's correct. If it then works within a |
||
} | ||
|
||
$namespaceLine = isset($context['namespace']) ? "\nnamespace {$context['namespace']};\n" : ''; | ||
|
||
return <<<EOL | ||
<?php | ||
$namespaceLine | ||
use Symfony\Component\Serializer\Exception\CircularReferenceException; | ||
use Symfony\Component\Serializer\Normalizer\CircularReferenceTrait; | ||
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; | ||
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait; | ||
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; | ||
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; | ||
|
||
/** | ||
* This class is generated. | ||
* Please do not update it manually. | ||
*/ | ||
class {$context['class']} implements NormalizerInterface, NormalizerAwareInterface | ||
{ | ||
protected \$defaultContext = array( | ||
ObjectNormalizer::CIRCULAR_REFERENCE_LIMIT => 1, | ||
); | ||
|
||
use CircularReferenceTrait, NormalizerAwareTrait; | ||
|
||
public function __construct(array \$defaultContext = array()) | ||
{ | ||
\$this->defaultContext = array_merge(\$this->defaultContext, \$defaultContext); | ||
} | ||
|
||
{$this->generateNormalizeMethod($reflectionClass)} | ||
|
||
{$this->generateSupportsNormalizationMethod($reflectionClass)} | ||
} | ||
EOL; | ||
} | ||
|
||
/** | ||
* Generates the {@see NormalizerInterface::normalize} method. | ||
*/ | ||
private function generateNormalizeMethod(\ReflectionClass $reflectionClass): string | ||
{ | ||
return <<<EOL | ||
public function normalize(\$object, \$format = null, array \$context = array()) | ||
{ | ||
{$this->generateNormalizeMethodInner($reflectionClass)} | ||
} | ||
EOL; | ||
} | ||
|
||
private function generateNormalizeMethodInner(\ReflectionClass $reflectionClass): string | ||
{ | ||
$code = <<<EOL | ||
|
||
if (\$this->isCircularReference(\$object, \$context)) { | ||
return \$this->handleCircularReference(\$object, \$format, \$context); | ||
} | ||
|
||
\$groups = isset(\$context[ObjectNormalizer::GROUPS]) && is_array(\$context[ObjectNormalizer::GROUPS]) ? \$context[ObjectNormalizer::GROUPS] : null; | ||
|
||
\$output = array(); | ||
EOL; | ||
|
||
$attributesMetadata = $this->classMetadataFactory->getMetadataFor($reflectionClass->name)->getAttributesMetadata(); | ||
$maxDepthCode = ''; | ||
foreach ($attributesMetadata as $attributeMetadata) { | ||
if (null === $maxDepth = $attributeMetadata->getMaxDepth()) { | ||
continue; | ||
} | ||
|
||
$key = sprintf(ObjectNormalizer::DEPTH_KEY_PATTERN, $reflectionClass->name, $attributeMetadata->name); | ||
$maxDepthCode .= <<<EOL | ||
isset(\$context['{$key}']) ? ++\$context['{$key}'] : \$context['{$key}'] = 1; | ||
EOL; | ||
} | ||
|
||
if ($maxDepthCode) { | ||
$code .= <<<EOL | ||
|
||
if (\$context[ObjectNormalizer::ENABLE_MAX_DEPTH] ?? \$this->defaultContext[ObjectNormalizer::ENABLE_MAX_DEPTH]) {{$maxDepthCode} | ||
} | ||
|
||
EOL; | ||
} | ||
|
||
foreach ($attributesMetadata as $attributeMetadata) { | ||
$code .= <<<EOL | ||
|
||
\$attributes = \$context[ObjectNormalizer::ATTRIBUTES] ?? \$this->defaultContext[ObjectNormalizer::ATTRIBUTES] ?? null; | ||
if ((null === \$groups | ||
EOL; | ||
|
||
if ($attributeMetadata->groups) { | ||
$code .= sprintf(" || array_intersect(\$groups, array('%s'))", implode("', '", $attributeMetadata->groups)); | ||
} | ||
$code .= ')'; | ||
|
||
$code .= " && (null === \$attributes || isset(\$attributes['{$attributeMetadata->name}']) || (is_array(\$attributes) && in_array('{$attributeMetadata->name}', \$attributes, true)))"; | ||
|
||
if (null !== $maxDepth = $attributeMetadata->getMaxDepth()) { | ||
$key = sprintf(ObjectNormalizer::DEPTH_KEY_PATTERN, $reflectionClass->name, $attributeMetadata->name); | ||
$code .= " && (!isset(\$context['{$key}']) || {$maxDepth} >= \$context['{$key}'])"; | ||
} | ||
|
||
$code .= ') {'; | ||
|
||
$value = $this->generateGetAttributeValueExpression($attributeMetadata->name, $reflectionClass); | ||
$code .= <<<EOL | ||
|
||
\$value = {$value}; | ||
if (is_scalar(\$value)) { | ||
\$output['{$attributeMetadata->name}'] = \$value; | ||
} else { | ||
\$subContext = \$context; | ||
GuilhemN marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (isset(\$attributes['{$attributeMetadata->name}'])) { | ||
\$subContext[ObjectNormalizer::ATTRIBUTES] = \$attributes['{$attributeMetadata->name}']; | ||
} else { | ||
unset(\$subContext[ObjectNormalizer::ATTRIBUTES]); | ||
} | ||
|
||
\$output['{$attributeMetadata->name}'] = \$this->normalizer->normalize(\$value, \$format, \$subContext); | ||
} | ||
} | ||
EOL; | ||
} | ||
|
||
$code .= <<<EOL | ||
|
||
|
||
return \$output; | ||
EOL; | ||
|
||
return $code; | ||
} | ||
|
||
private function generateGetAttributeValueExpression(string $property, \ReflectionClass $reflectionClass): string | ||
{ | ||
$camelProp = $this->camelize($property); | ||
|
||
foreach ($methods = array("get$camelProp", lcfirst($camelProp), "is$camelProp", "has$camelProp)") as $method) { | ||
if ($reflectionClass->hasMethod($method) && $reflectionClass->getMethod($method)) { | ||
return sprintf('$object->%s()', $method); | ||
} | ||
} | ||
|
||
if ($reflectionClass->hasProperty($property) && $reflectionClass->getProperty($property)->isPublic()) { | ||
return sprintf('$object->%s', $property); | ||
} | ||
|
||
if ($reflectionClass->hasMethod('__get') && $reflectionClass->getMethod('__get')) { | ||
return sprintf('$object->__get(\'%s\')', $property); | ||
} | ||
|
||
throw new \DomainException(sprintf('Neither the property "%s" nor one of the methods "%s()", "__get()" exist and have public access in class "%s".', $property, implode('()", "', $methods), $reflectionClass->name)); | ||
} | ||
|
||
private function generateSupportsNormalizationMethod(\ReflectionClass $reflectionClass): string | ||
{ | ||
$instanceof = '\\'.$reflectionClass->name; | ||
|
||
return <<<EOL | ||
public function supportsNormalization(\$data, \$format = null, array \$context = array()) | ||
{ | ||
return \$data instanceof {$instanceof}; | ||
} | ||
EOL; | ||
} | ||
|
||
private function camelize(string $string): string | ||
{ | ||
return str_replace(' ', '', ucwords(str_replace('_', ' ', $string))); | ||
} | ||
} |
Uh oh!
There was an error while loading. Please reload this page.