UidNormalizer.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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\Normalizer;
  11. use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
  12. use Symfony\Component\Uid\AbstractUid;
  13. use Symfony\Component\Uid\Ulid;
  14. use Symfony\Component\Uid\Uuid;
  15. final class UidNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
  16. {
  17. /**
  18. * {@inheritdoc}
  19. */
  20. public function normalize($object, string $format = null, array $context = [])
  21. {
  22. return (string) $object;
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function supportsNormalization($data, string $format = null)
  28. {
  29. return $data instanceof AbstractUid;
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function denormalize($data, string $type, string $format = null, array $context = [])
  35. {
  36. try {
  37. return Ulid::class === $type ? Ulid::fromString($data) : Uuid::fromString($data);
  38. } catch (\InvalidArgumentException $exception) {
  39. throw new NotNormalizableValueException(sprintf('The data is not a valid "%s" string representation.', $type));
  40. }
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function supportsDenormalization($data, string $type, string $format = null)
  46. {
  47. return is_a($type, AbstractUid::class, true);
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function hasCacheableSupportsMethod(): bool
  53. {
  54. return __CLASS__ === static::class;
  55. }
  56. }