Webservice.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace WebserviceBundle\Services;
  3. class Webservice
  4. {
  5. protected $serviceContainer;
  6. public function __construct($serviceContainer)
  7. {
  8. $this->serviceContainer = $serviceContainer;
  9. }
  10. /**
  11. * @param string $webservice
  12. * @param array $params
  13. * @return array
  14. */
  15. public function getChoices($webservice, $params = array())
  16. {
  17. $choices = array();
  18. $results = $this->getArray($webservice, $params);
  19. foreach ($results as $row) {
  20. $choices[$row['name']] = $row['id'];
  21. }
  22. return $choices;
  23. }
  24. /**
  25. * @param string $webservice
  26. * @param array $params
  27. * @return array
  28. */
  29. public function getArray($webservice, $params = array())
  30. {
  31. $results = array();
  32. if ($this->serviceContainer->hasParameter($webservice)) {
  33. $url = $this->serviceContainer->getParameter($webservice);
  34. $url .= '?filters[qb-criteria]';
  35. foreach ($params as $param => $value) {
  36. $url .= "&filters[{$param}]=$value";
  37. }
  38. try {
  39. $results = json_decode(file_get_contents($url), true);
  40. } catch (\Exception $ex) {
  41. }
  42. }
  43. return $results;
  44. }
  45. /**
  46. * @param string $webservice
  47. * @param array $filters
  48. * @param array $order_by
  49. * @param integer $limit
  50. * @param integer $offset
  51. * @return array
  52. */
  53. public function getData($webservice, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  54. {
  55. if ($this->serviceContainer->hasParameter($webservice)) {
  56. $url = $this->serviceContainer->getParameter($webservice) . "?";
  57. if($filters) {
  58. $url .= http_build_query(array('filters' => $filters));
  59. }
  60. if($order_by) {
  61. $url .= http_build_query(array('order_by' => $order_by));
  62. }
  63. if($limit) {
  64. $url .= "&limit={$limit}";
  65. }
  66. if($offset) {
  67. $url .= "&offset={$offset}";
  68. }
  69. $data = array();
  70. try {
  71. $data = json_decode(file_get_contents($url), true);
  72. } catch (\Exception $ex) {
  73. }
  74. //$data['url'] = $url;
  75. return $data;
  76. }
  77. return array();
  78. }
  79. /**
  80. * @param string $webservice
  81. * @param int $id
  82. * @return string
  83. */
  84. public function getById($webservice, $id)
  85. {
  86. $result = $this->getArray($webservice, array(
  87. 'id' => $id
  88. ));
  89. return isset($result[0]) ? "{$result[0]['id']} - {$result[0]['name']}" : $id;
  90. }
  91. }