ClassDiscriminatorMapping.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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;
  11. /**
  12. * @author Samuel Roze <samuel.roze@gmail.com>
  13. */
  14. class ClassDiscriminatorMapping
  15. {
  16. private $typeProperty;
  17. private $typesMapping;
  18. public function __construct(string $typeProperty, array $typesMapping = [])
  19. {
  20. $this->typeProperty = $typeProperty;
  21. $this->typesMapping = $typesMapping;
  22. uasort($this->typesMapping, static function (string $a, string $b): int {
  23. if (is_a($a, $b, true)) {
  24. return -1;
  25. }
  26. if (is_a($b, $a, true)) {
  27. return 1;
  28. }
  29. return 0;
  30. });
  31. }
  32. public function getTypeProperty(): string
  33. {
  34. return $this->typeProperty;
  35. }
  36. public function getClassForType(string $type): ?string
  37. {
  38. return $this->typesMapping[$type] ?? null;
  39. }
  40. /**
  41. * @param object|string $object
  42. */
  43. public function getMappedObjectType($object): ?string
  44. {
  45. foreach ($this->typesMapping as $type => $typeClass) {
  46. if (is_a($object, $typeClass)) {
  47. return $type;
  48. }
  49. }
  50. return null;
  51. }
  52. public function getTypesMapping(): array
  53. {
  54. return $this->typesMapping;
  55. }
  56. }