Json.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * JSON deserializer of REST request content.
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\Framework\Webapi\Rest\Request\Deserializer;
  9. use Magento\Framework\App\State;
  10. use Magento\Framework\Phrase;
  11. class Json implements \Magento\Framework\Webapi\Rest\Request\DeserializerInterface
  12. {
  13. /**
  14. * @var \Magento\Framework\Json\Decoder
  15. * @deprecated 101.0.0
  16. */
  17. protected $decoder;
  18. /**
  19. * @var State
  20. */
  21. protected $_appState;
  22. /**
  23. * @var \Magento\Framework\Serialize\Serializer\Json
  24. */
  25. private $serializer;
  26. /**
  27. * @param \Magento\Framework\Json\Decoder $decoder
  28. * @param State $appState
  29. * @param \Magento\Framework\Serialize\Serializer\Json|null $serializer
  30. * @throws \RuntimeException
  31. */
  32. public function __construct(
  33. \Magento\Framework\Json\Decoder $decoder,
  34. State $appState,
  35. \Magento\Framework\Serialize\Serializer\Json $serializer = null
  36. ) {
  37. $this->decoder = $decoder;
  38. $this->_appState = $appState;
  39. $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance()
  40. ->get(\Magento\Framework\Serialize\Serializer\Json::class);
  41. }
  42. /**
  43. * Parse Request body into array of params.
  44. *
  45. * @param string $encodedBody Posted content from request.
  46. * @return array|null Return NULL if content is invalid.
  47. * @throws \InvalidArgumentException
  48. * @throws \Magento\Framework\Webapi\Exception If decoding error was encountered.
  49. */
  50. public function deserialize($encodedBody)
  51. {
  52. if (!is_string($encodedBody)) {
  53. throw new \InvalidArgumentException(
  54. sprintf('"%s" data type is invalid. String is expected.', gettype($encodedBody))
  55. );
  56. }
  57. try {
  58. $decodedBody = $this->serializer->unserialize($encodedBody);
  59. } catch (\InvalidArgumentException $e) {
  60. if ($this->_appState->getMode() !== State::MODE_DEVELOPER) {
  61. throw new \Magento\Framework\Webapi\Exception(new Phrase('Decoding error.'));
  62. } else {
  63. throw new \Magento\Framework\Webapi\Exception(
  64. new Phrase(
  65. 'Decoding error: %1%2%3%4',
  66. [PHP_EOL, $e->getMessage(), PHP_EOL, $e->getTraceAsString()]
  67. )
  68. );
  69. }
  70. }
  71. return $decodedBody;
  72. }
  73. }