mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-09-17 12:14:58 +00:00
72 lines
2.2 KiB
PHP
72 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace Chill\MainBundle\Serializer\Normalizer;
|
|
|
|
use Symfony\Component\Serializer\Normalizer\ContextAwareDenormalizerInterface;
|
|
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
|
|
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
|
|
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
|
|
use Symfony\Component\Serializer\Exception\RuntimeException;
|
|
|
|
|
|
/**
|
|
* Denormalize an object given a list of supported class
|
|
*/
|
|
class DiscriminatedObjectDenormalizer implements ContextAwareDenormalizerInterface, DenormalizerAwareInterface
|
|
{
|
|
use DenormalizerAwareTrait;
|
|
|
|
/**
|
|
* The type to set for enabling this type
|
|
*/
|
|
public const TYPE = '@multi';
|
|
|
|
/**
|
|
* Should be present in context and contains an array of
|
|
* allowed types.
|
|
*/
|
|
public const ALLOWED_TYPES = 'denormalize_multi.allowed_types';
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function denormalize($data, string $type, string $format = null, array $context = [])
|
|
{
|
|
foreach ($context[self::ALLOWED_TYPES] as $localType) {
|
|
if ($this->denormalizer->supportsDenormalization($data, $localType, $format)) {
|
|
try {
|
|
return $this->denormalizer->denormalize($data, $localType, $format, $context); } catch (RuntimeException $e) {
|
|
$lastException = $e;
|
|
}
|
|
}
|
|
}
|
|
|
|
throw new RuntimeException(sprintf("Could not find any denormalizer for those ".
|
|
"ALLOWED_TYPES: %s", \implode(", ", $context[self::ALLOWED_TYPES])));
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function supportsDenormalization($data, string $type, string $format = null, array $context = [])
|
|
{
|
|
if (self::TYPE !== $type) {
|
|
return false;
|
|
}
|
|
|
|
if (0 === count($context[self::ALLOWED_TYPES] ?? [])) {
|
|
throw new \LogicException("The context should contains a list of
|
|
allowed types");
|
|
}
|
|
|
|
foreach ($context[self::ALLOWED_TYPES] as $localType) {
|
|
if ($this->denormalizer->supportsDenormalization($data, $localType, $format)) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
}
|