DeserializerFactory.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * Factory of REST request deserializers.
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\Framework\Webapi\Rest\Request;
  9. use Magento\Framework\Phrase;
  10. class DeserializerFactory
  11. {
  12. /**
  13. * @var \Magento\Framework\ObjectManagerInterface
  14. */
  15. protected $_objectManager;
  16. /**
  17. * @var array
  18. */
  19. protected $_deserializers;
  20. /**
  21. * @param \Magento\Framework\ObjectManagerInterface $objectManager
  22. * @param array $deserializers
  23. */
  24. public function __construct(
  25. \Magento\Framework\ObjectManagerInterface $objectManager,
  26. array $deserializers = []
  27. ) {
  28. $this->_objectManager = $objectManager;
  29. $this->_deserializers = $deserializers;
  30. }
  31. /**
  32. * Retrieve proper deserializer for the specified content type.
  33. *
  34. * @param string $contentType
  35. * @return \Magento\Framework\Webapi\Rest\Request\DeserializerInterface
  36. * @throws \LogicException|\Magento\Framework\Webapi\Exception
  37. */
  38. public function get($contentType)
  39. {
  40. if (empty($this->_deserializers)) {
  41. throw new \LogicException('Request deserializer adapter is not set.');
  42. }
  43. foreach ($this->_deserializers as $deserializerMetadata) {
  44. $deserializerType = $deserializerMetadata['type'];
  45. if ($deserializerType == $contentType) {
  46. $deserializerClass = $deserializerMetadata['model'];
  47. break;
  48. }
  49. }
  50. if (!isset($deserializerClass) || empty($deserializerClass)) {
  51. throw new \Magento\Framework\Webapi\Exception(
  52. new Phrase('Server cannot understand Content-Type HTTP header media type %1', [$contentType])
  53. );
  54. }
  55. $deserializer = $this->_objectManager->get($deserializerClass);
  56. if (!$deserializer instanceof \Magento\Framework\Webapi\Rest\Request\DeserializerInterface) {
  57. throw new \LogicException(
  58. 'The deserializer must implement "Magento\Framework\Webapi\Rest\Request\DeserializerInterface".'
  59. );
  60. }
  61. return $deserializer;
  62. }
  63. }