ClassMetadataFactoryCompiler.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Serializer\Mapping\Factory;
  11. use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
  12. use Symfony\Component\VarExporter\VarExporter;
  13. /**
  14. * @author Fabien Bourigault <bourigaultfabien@gmail.com>
  15. */
  16. final class ClassMetadataFactoryCompiler
  17. {
  18. /**
  19. * @param ClassMetadataInterface[] $classMetadatas
  20. */
  21. public function compile(array $classMetadatas): string
  22. {
  23. return <<<EOF
  24. <?php
  25. // This file has been auto-generated by the Symfony Serializer Component.
  26. return [{$this->generateDeclaredClassMetadata($classMetadatas)}
  27. ];
  28. EOF;
  29. }
  30. /**
  31. * @param ClassMetadataInterface[] $classMetadatas
  32. */
  33. private function generateDeclaredClassMetadata(array $classMetadatas): string
  34. {
  35. $compiled = '';
  36. foreach ($classMetadatas as $classMetadata) {
  37. $attributesMetadata = [];
  38. foreach ($classMetadata->getAttributesMetadata() as $attributeMetadata) {
  39. $attributesMetadata[$attributeMetadata->getName()] = [
  40. $attributeMetadata->getGroups(),
  41. $attributeMetadata->getMaxDepth(),
  42. $attributeMetadata->getSerializedName(),
  43. ];
  44. }
  45. $classDiscriminatorMapping = $classMetadata->getClassDiscriminatorMapping() ? [
  46. $classMetadata->getClassDiscriminatorMapping()->getTypeProperty(),
  47. $classMetadata->getClassDiscriminatorMapping()->getTypesMapping(),
  48. ] : null;
  49. $compiled .= sprintf("\n'%s' => %s,", $classMetadata->getName(), VarExporter::export([
  50. $attributesMetadata,
  51. $classDiscriminatorMapping,
  52. ]));
  53. }
  54. return $compiled;
  55. }
  56. }