Request.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace ModulesGarden\ProxmoxAddon\App\Libs\Api\OpenSRS;
  3. use Spyc;
  4. class Request
  5. {
  6. /**
  7. * Process an OpenSRS Request.
  8. *
  9. * @param string $format input format (xml, json, array)
  10. * @param string $data data
  11. */
  12. public function process($format = '', $data = '')
  13. {
  14. if (empty($data))
  15. {
  16. throw new Exception('OSRS Error - No data found.');
  17. return;
  18. }
  19. $dataArray = [];
  20. switch (strtolower($format))
  21. {
  22. case 'array':
  23. $dataArray = $data;
  24. break;
  25. case 'json':
  26. $json = str_replace('\\"', '"', $data); // Replace \" with " for JSON that comes from Javascript
  27. $dataArray = json_decode($json, true);
  28. break;
  29. case 'yaml':
  30. $dataArray = Spyc::YAMLLoad($data);
  31. break;
  32. default:
  33. $dataArray = $data;
  34. }
  35. // Convert associative array to object
  36. $dataObject = $this->array2object($dataArray);
  37. $classCall = null;
  38. $classCall = RequestFactory::build($dataObject->func, $format, $dataObject);
  39. return $classCall;
  40. }
  41. /**
  42. * Method to convert Array -> Object -> Array.
  43. *
  44. * @param hash $data Containing array object
  45. *
  46. * @return stdClass Object $object Containing stdClass object
  47. *
  48. * @since 3.4
  49. */
  50. public function array2object($data)
  51. {
  52. if (is_array($data))
  53. {
  54. $data = json_decode(json_encode($data));
  55. }
  56. return $data;
  57. }
  58. public function convertArray2Formatted($type = '', $data = '')
  59. {
  60. $resultString = '';
  61. if ($type == 'json')
  62. {
  63. $resultString = json_encode($data);
  64. }
  65. if ($type == 'yaml')
  66. {
  67. $resultString = Spyc::YAMLDump($data);
  68. }
  69. return $resultString;
  70. }
  71. public function convertFormatted2array($type = '', $data = '')
  72. {
  73. $resultArray = '';
  74. if ($type == 'json')
  75. {
  76. $resultArray = json_decode($data, true);
  77. }
  78. if ($type == 'yaml')
  79. {
  80. $resultArray = Spyc::YAMLLoad($data);
  81. }
  82. return $resultArray;
  83. }
  84. public function array_filter_recursive($input)
  85. {
  86. foreach ($input as &$value)
  87. {
  88. if (is_array($value))
  89. {
  90. $value = $this->array_filter_recursive($value);
  91. }
  92. }
  93. return array_filter($input);
  94. }
  95. }