Webservice.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. }
  161. return $data;
  162. }
  163. /**
  164. * @param string $webservice
  165. * @param array $filters
  166. * @param array $order_by
  167. * @param int $limit
  168. * @param int $offset
  169. *
  170. * @return string
  171. */
  172. public function buildUrl($webservice, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  173. {
  174. $url = $webservice . '?';
  175. if ($this->serviceContainer->hasParameter($webservice)) {
  176. $url = $this->serviceContainer->getParameter($webservice) . '?';
  177. }
  178. if ($filters) {
  179. $url .= http_build_query(array('filters' => $filters));
  180. }
  181. if ($order_by) {
  182. $url .= '&' . http_build_query(array('order_by' => $order_by));
  183. }
  184. if ($limit) {
  185. $url .= "&limit={$limit}";
  186. }
  187. if ($offset) {
  188. $url .= "&offset={$offset}";
  189. }
  190. return $url;
  191. }
  192. /**
  193. * @param string $webservice
  194. * @param int $id
  195. *
  196. * @return string
  197. */
  198. public function getById($webservice, $id)
  199. {
  200. $result = $this->getArray($webservice, array(
  201. 'id' => $id
  202. ));
  203. return isset($result[0]) && isset($result[0]['id']) && isset($result[0]['name'])
  204. ? "{$result[0]['id']} - {$result[0]['name']}"
  205. : $id;
  206. }
  207. /**
  208. * @param string $webservice
  209. * @param int $id
  210. * @param array $data
  211. *
  212. * @return array
  213. */
  214. public function putData($webservice, $id, $data)
  215. {
  216. if ($this->serviceContainer->hasParameter($webservice)) {
  217. $url = str_replace(".json", "/{$id}", $this->serviceContainer->getParameter($webservice));
  218. $data_string = json_encode($data);
  219. $ch = curl_init($url);
  220. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  221. curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  222. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
  223. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  224. try {
  225. $return = curl_exec($ch);
  226. } catch (\Exception $ex) {
  227. return array("error" => "Connection Error.");
  228. }
  229. if ($return) {
  230. return json_decode($return, true);
  231. } else {
  232. return array("error" => "Transaction Error.");
  233. }
  234. }
  235. return array("error" => "Webservice({$webservice}) not found.");
  236. }
  237. public function buildUrlForId($ws, $id = null, $extra = null)
  238. {
  239. $url = $this->serviceContainer->getParameter($ws);
  240. if (!is_null($id)) {
  241. $url = str_replace(".json", "/{$id}", $url);
  242. }
  243. return $url . $extra;
  244. }
  245. /**
  246. * @return ContainerInterface
  247. */
  248. public function getServiceContainer()
  249. {
  250. return $this->serviceContainer;
  251. }
  252. /**
  253. * @return TokenStorage
  254. */
  255. public function getSecurityTokenStorage()
  256. {
  257. return $this->securityTokenStorage;
  258. }
  259. /**
  260. * @return Curl
  261. */
  262. public function getHttpClient()
  263. {
  264. return $this->httpClient;
  265. }
  266. /**
  267. * @param string $webservice
  268. * @param int $id
  269. *
  270. * @return string Funcion que retorna todos los datos del objeto.
  271. */
  272. public function getByIdData($webservice, $id)
  273. {
  274. $result = $this->getArray($webservice, array(
  275. 'id' => $id
  276. ));
  277. return isset($result[0]) ? $result[0] : $id;
  278. }
  279. }