Skip to content

Instantly share code, notes, and snippets.

@Nemo64
Created September 26, 2022 14:49
Show Gist options
  • Save Nemo64/a21a416513361ea7e3aae40addcc7065 to your computer and use it in GitHub Desktop.
Save Nemo64/a21a416513361ea7e3aae40addcc7065 to your computer and use it in GitHub Desktop.
This normalizer will normalize all properties of an object, regardless of visibility.
<?php
namespace App\Serializer;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
/**
* This normalizer will normalize all properties of an object, regardless of visibility.
* It will not use methods, just reflection access to properties.
*
* This is usually not a good idea, which is why it is disabled by default.
* Use context: [AggressiveObjectNormalizer::class => true] to enable it.
*/
class AggressiveObjectNormalizer extends AbstractObjectNormalizer
{
public function supportsNormalization(mixed $data, string $format = null, array $context = [] )
{
if (empty($context[__CLASS__])) {
return false;
}
return parent::supportsNormalization($data, $format);
}
public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = [])
{
if (empty($context[__CLASS__])) {
return false;
}
return parent::supportsDenormalization($data, $type, $format);
}
protected function extractAttributes(object $object, string $format = null, array $context = [])
{
$attributes = [];
foreach ((new \ReflectionClass($object))->getProperties() as $property) {
$attributes[$property->name] = true;
}
return array_keys($attributes);
}
protected function getAttributeValue(object $object, string $attribute, string $format = null, array $context = [])
{
return (new \ReflectionProperty($object, $attribute))->getValue($object);
}
protected function setAttributeValue(object $object, string $attribute, mixed $value, string $format = null, array $context = [])
{
(new \ReflectionProperty($object, $attribute))->setValue($object, $value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment