DateTimeZoneNormalizer.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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\InvalidArgumentException;
  12. use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
  13. /**
  14. * Normalizes a {@see \DateTimeZone} object to a timezone string.
  15. *
  16. * @author Jérôme Desjardins <jewome62@gmail.com>
  17. */
  18. class DateTimeZoneNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
  19. {
  20. /**
  21. * {@inheritdoc}
  22. *
  23. * @throws InvalidArgumentException
  24. *
  25. * @return string
  26. */
  27. public function normalize($object, string $format = null, array $context = [])
  28. {
  29. if (!$object instanceof \DateTimeZone) {
  30. throw new InvalidArgumentException('The object must be an instance of "\DateTimeZone".');
  31. }
  32. return $object->getName();
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function supportsNormalization($data, string $format = null)
  38. {
  39. return $data instanceof \DateTimeZone;
  40. }
  41. /**
  42. * {@inheritdoc}
  43. *
  44. * @throws NotNormalizableValueException
  45. *
  46. * @return \DateTimeZone
  47. */
  48. public function denormalize($data, string $type, string $format = null, array $context = [])
  49. {
  50. if ('' === $data || null === $data) {
  51. throw new NotNormalizableValueException('The data is either an empty string or null, you should pass a string that can be parsed as a DateTimeZone.');
  52. }
  53. try {
  54. return new \DateTimeZone($data);
  55. } catch (\Exception $e) {
  56. throw new NotNormalizableValueException($e->getMessage(), $e->getCode(), $e);
  57. }
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function supportsDenormalization($data, string $type, string $format = null)
  63. {
  64. return \DateTimeZone::class === $type;
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function hasCacheableSupportsMethod(): bool
  70. {
  71. return __CLASS__ === static::class;
  72. }
  73. }