Webservice.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php
  2. namespace WebserviceBundle\Services;
  3. use Buzz\Client\Curl;
  4. use Buzz\Message\Request as HttpRequest;
  5. use Buzz\Message\RequestInterface as HttpRequestInterface;
  6. use Buzz\Message\Response as HttpResponse;
  7. use Symfony\Component\DependencyInjection\ContainerInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. class Webservice
  10. {
  11. /**
  12. * @var ContainerInterface
  13. */
  14. protected $serviceContainer;
  15. /**
  16. * @var TokenStorage
  17. */
  18. protected $securityTokenStorage;
  19. /**
  20. * @var Curl
  21. */
  22. protected $httpClient;
  23. /**
  24. * @param ContainerInterface $serviceContainer
  25. * @param TokenStorageInterface $securityTokenStorage
  26. * @param Curl $httpClient
  27. */
  28. public function __construct(ContainerInterface $serviceContainer, TokenStorageInterface $securityTokenStorage, Curl $httpClient)
  29. {
  30. $this->serviceContainer = $serviceContainer;
  31. $this->securityTokenStorage = $securityTokenStorage;
  32. $this->httpClient = $httpClient;
  33. }
  34. /**
  35. * @param string $webservice
  36. * @param array $params
  37. *
  38. * @return array
  39. */
  40. public function getChoices($webservice, $params = array())
  41. {
  42. $choices = array();
  43. $results = $this->getArray($webservice, $params);
  44. foreach ($results as $row) {
  45. if (isset($row['name']) && isset($row['id'])) {
  46. $choices[$row['name']] = $row['id'];
  47. }
  48. }
  49. return $choices;
  50. }
  51. /**
  52. * @param string $webservice
  53. * @param array $params
  54. *
  55. * @return array
  56. */
  57. public function getArray($webservice, $params = array())
  58. {
  59. $results = array();
  60. if ($this->serviceContainer->hasParameter($webservice)) {
  61. $url = $this->serviceContainer->getParameter($webservice);
  62. $url .= '?filters[qb-criteria]';
  63. foreach ($params as $param => $value) {
  64. $url .= "&filters[{$param}]=$value";
  65. }
  66. try {
  67. $results = json_decode($this->makeGetRequest($url), true);
  68. } catch (\Exception $ex) {
  69. }
  70. }
  71. return (array)$results;
  72. }
  73. /**
  74. * @param string $url
  75. * @param string $method
  76. * @param array $data
  77. *
  78. * @return HttpResponse
  79. */
  80. public function makeRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array())
  81. {
  82. $request = new HttpRequest($method, $url);
  83. $headers = array();
  84. if (!empty($data)) {
  85. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  86. $request->setContent(http_build_query($data));
  87. }
  88. $request->setHeaders($headers);
  89. $response = new HttpResponse();
  90. $this->httpClient->send($request, $response);
  91. return $response->getContent();
  92. }
  93. /**
  94. * @param string $url
  95. * @param string $method
  96. * @param array $data
  97. * @param array $credentials
  98. *
  99. * @return HttpResponse
  100. */
  101. public function makeGetRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array(), $credentials = array())
  102. {
  103. $headers = array();
  104. if ($token = $this->securityTokenStorage->getToken()) {
  105. if (method_exists($token, 'getAccessToken')) {
  106. $headers[] = 'Authorization: Bearer ' . $token->getAccessToken();
  107. }
  108. } elseif (!empty($credentials) && isset($credentials['username']) && isset($credentials['password'])) {
  109. $headers[] = 'Authorization: Basic ' . base64_encode($credentials['username'] . ":" . $credentials['password']);
  110. } else {
  111. return '';
  112. }
  113. $request = new HttpRequest($method, $url);
  114. if (!empty($data)) {
  115. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  116. $request->setContent(http_build_query($data));
  117. }
  118. $request->setHeaders($headers);
  119. $response = new HttpResponse();
  120. $this->httpClient->send($request, $response);
  121. $response = $response->getContent();
  122. return $response;
  123. }
  124. /**
  125. * @param string $url
  126. * @param array $filters
  127. * @param array $order_by
  128. * @param integer $limit
  129. * @param integer $offset
  130. *
  131. * @return array
  132. */
  133. public function getData($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  134. {
  135. $data = array();
  136. try {
  137. $url = $this->buildUrl($url, $filters, $order_by, $limit, $offset);
  138. $data = json_decode($this->makeGetRequest($url), true);
  139. } catch (\Exception $ex) {
  140. // TODO : Loguear esta exception o lanzarla.
  141. }
  142. return $data;
  143. }
  144. /**
  145. * @param string $url
  146. * @param array $filters
  147. * @param array $order_by
  148. * @param integer $limit
  149. * @param integer $offset
  150. *
  151. * @return array
  152. */
  153. public function get($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  154. {
  155. $data = array();
  156. try {
  157. $url = $this->buildUrl($url, $filters, $order_by, $limit, $offset);
  158. $data = json_decode($this->makeRequest($url), true);
  159. } catch (\Exception $ex) {}
  160. return $data;
  161. }
  162. /**
  163. * @param string $webservice
  164. * @param array $filters
  165. * @param array $order_by
  166. * @param int $limit
  167. * @param int $offset
  168. *
  169. * @return string
  170. */
  171. public function buildUrl($webservice, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  172. {
  173. $url = $webservice . '?';
  174. if ($this->serviceContainer->hasParameter($webservice)) {
  175. $url = $this->serviceContainer->getParameter($webservice) . '?';
  176. }
  177. if ($filters) {
  178. $url .= http_build_query(array('filters' => $filters));
  179. }
  180. if ($order_by) {
  181. $url .= '&' . http_build_query(array('order_by' => $order_by));
  182. }
  183. if ($limit) {
  184. $url .= "&limit={$limit}";
  185. }
  186. if ($offset) {
  187. $url .= "&offset={$offset}";
  188. }
  189. return $url;
  190. }
  191. /**
  192. * @param string $webservice
  193. * @param int $id
  194. *
  195. * @return string
  196. */
  197. public function getById($webservice, $id)
  198. {
  199. $result = $this->getArray($webservice, array(
  200. 'id' => $id
  201. ));
  202. return isset($result[0]) && isset($result[0]['id']) && isset($result[0]['name'])
  203. ? "{$result[0]['id']} - {$result[0]['name']}"
  204. : $id;
  205. }
  206. /**
  207. * @param string $webservice
  208. * @param int $id
  209. * @param array $data
  210. *
  211. * @return array
  212. */
  213. public function putData($webservice, $id, $data)
  214. {
  215. if ($this->serviceContainer->hasParameter($webservice)) {
  216. $url = str_replace(".json", "/{$id}", $this->serviceContainer->getParameter($webservice));
  217. $data_string = json_encode($data);
  218. $ch = curl_init($url);
  219. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  220. curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  221. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
  222. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  223. try {
  224. $return = curl_exec($ch);
  225. } catch (\Exception $ex) {
  226. return array("error" => "Connection Error.");
  227. }
  228. if ($return) {
  229. return json_decode($return, true);
  230. } else {
  231. return array("error" => "Transaction Error.");
  232. }
  233. }
  234. return array("error" => "Webservice({$webservice}) not found.");
  235. }
  236. public function buildUrlForId($ws,$id = null, $extra= null){
  237. $url = $this->serviceContainer->getParameter($ws);
  238. if(!is_null($id)){
  239. $url = str_replace(".json", "/{$id}", $url);
  240. }
  241. return $url . $extra;
  242. }
  243. /**
  244. * @return ContainerInterface
  245. */
  246. public function getServiceContainer()
  247. {
  248. return $this->serviceContainer;
  249. }
  250. /**
  251. * @return TokenStorage
  252. */
  253. public function getSecurityTokenStorage()
  254. {
  255. return $this->securityTokenStorage;
  256. }
  257. /**
  258. * @return Curl
  259. */
  260. public function getHttpClient()
  261. {
  262. return $this->httpClient;
  263. }
  264. }