Base64Json.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. /**
  8. * Class for serializing data first to json string and then to base64 string.
  9. *
  10. * May be used for cases when json encoding results with a string,
  11. * which contains characters, which are unacceptable by client.
  12. */
  13. class Base64Json implements \Magento\Framework\Serialize\SerializerInterface
  14. {
  15. /**
  16. * @inheritdoc
  17. */
  18. public function serialize($data)
  19. {
  20. return base64_encode(json_encode($data));
  21. }
  22. /**
  23. * Unserialize the given string with base64 and json.
  24. * Falls back to the json-only decoding on failure.
  25. *
  26. * @param string $string
  27. * @return string|int|float|bool|array|null
  28. */
  29. public function unserialize($string)
  30. {
  31. $result = json_decode(base64_decode($string), true);
  32. if (json_last_error() !== JSON_ERROR_NONE) {
  33. return json_decode($string, true);
  34. }
  35. return $result;
  36. }
  37. }