| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Serializer\DependencyInjection; |
| 13 |
|
| 14 |
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; |
| 15 |
use Symfony\Component\DependencyInjection\ContainerBuilder; |
| 16 |
use Symfony\Component\Serializer\Exception\MappingException; |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
final class AttributeMetadataPass implements CompilerPassInterface |
| 22 |
{ |
| 23 |
public function process(ContainerBuilder $container): void |
| 24 |
{ |
| 25 |
if (!$container->hasDefinition('serializer.mapping.attribute_loader')) { |
| 26 |
return; |
| 27 |
} |
| 28 |
|
| 29 |
$resolve = $container->getParameterBag()->resolveValue(...); |
| 30 |
$taggedClasses = []; |
| 31 |
foreach ($container->getDefinitions() as $id => $definition) { |
| 32 |
if (!$definition->hasTag('serializer.attribute_metadata')) { |
| 33 |
continue; |
| 34 |
} |
| 35 |
$class = $resolve($definition->getClass()); |
| 36 |
foreach ($definition->getTag('serializer.attribute_metadata') as $attributes) { |
| 37 |
if ($class !== $for = $attributes['for'] ?? $class) { |
| 38 |
$this->checkSourceMapsToTarget($container, $class, $for); |
| 39 |
} |
| 40 |
|
| 41 |
$taggedClasses[$for][$class] = true; |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
if (!$taggedClasses) { |
| 46 |
return; |
| 47 |
} |
| 48 |
|
| 49 |
ksort($taggedClasses); |
| 50 |
|
| 51 |
$container->getDefinition('serializer.mapping.attribute_loader') |
| 52 |
->replaceArgument(1, array_map('array_keys', $taggedClasses)); |
| 53 |
} |
| 54 |
|
| 55 |
private function checkSourceMapsToTarget(ContainerBuilder $container, string $source, string $target): void |
| 56 |
{ |
| 57 |
$source = $container->getReflectionClass($source); |
| 58 |
$target = $container->getReflectionClass($target); |
| 59 |
|
| 60 |
foreach ($source->getProperties() as $p) { |
| 61 |
if ($p->class === $source->name && !($target->hasProperty($p->name) && $target->getProperty($p->name)->class === $target->name)) { |
| 62 |
throw new MappingException(\sprintf('The property "%s" on "%s" is not present on "%s".', $p->name, $source->name, $target->name)); |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
foreach ($source->getMethods() as $m) { |
| 67 |
if ($m->class === $source->name && !($target->hasMethod($m->name) && $target->getMethod($m->name)->class === $target->name)) { |
| 68 |
throw new MappingException(\sprintf('The method "%s" on "%s" is not present on "%s".', $m->name, $source->name, $target->name)); |
| 69 |
} |
| 70 |
} |
| 71 |
} |
| 72 |
} |