Json.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Serialize\Serializer;
  7. use Magento\Framework\Serialize\SerializerInterface;
  8. /**
  9. * Serialize data to JSON, unserialize JSON encoded data
  10. *
  11. * @api
  12. * @since 101.0.0
  13. */
  14. class Json implements SerializerInterface
  15. {
  16. /**
  17. * @inheritDoc
  18. * @since 101.0.0
  19. */
  20. public function serialize($data)
  21. {
  22. $result = json_encode($data);
  23. if (false === $result) {
  24. throw new \InvalidArgumentException("Unable to serialize value. Error: " . json_last_error_msg());
  25. }
  26. return $result;
  27. }
  28. /**
  29. * @inheritDoc
  30. * @since 101.0.0
  31. */
  32. public function unserialize($string)
  33. {
  34. $result = json_decode($string, true);
  35. if (json_last_error() !== JSON_ERROR_NONE) {
  36. throw new \InvalidArgumentException("Unable to unserialize value. Error: " . json_last_error_msg());
  37. }
  38. return $result;
  39. }
  40. }