Webservice.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. * Retorna el resultado para utilizar en un choice form field
  36. *
  37. * @param string $webservice
  38. * @param array $params
  39. *
  40. * @return array
  41. */
  42. public function getChoices($webservice, $params = array())
  43. {
  44. $choices = array();
  45. $results = $this->getArray($webservice, $params);
  46. foreach ($results as $row) {
  47. if (isset($row['name']) && isset($row['id'])) {
  48. $choices[$row['name']] = $row['id'];
  49. }
  50. }
  51. return $choices;
  52. }
  53. /**
  54. * Retorna el resultado como un array
  55. *
  56. * @param string $webservice
  57. * @param array $params
  58. *
  59. * @return array
  60. */
  61. public function getArray($webservice, $params = array())
  62. {
  63. $results = array();
  64. if ($this->serviceContainer->hasParameter($webservice)) {
  65. try {
  66. // Por defecto agrega filters[qb-criteria] y limit=20
  67. $url = $this->buildUrl($webservice, $params, true);
  68. $results = json_decode($this->makeGetRequest($url), true);
  69. } catch (\Exception $ex) {
  70. var_dump($ex->getMessage());
  71. }
  72. }
  73. return (array)$results;
  74. }
  75. /**
  76. * @param string $url
  77. * @param string $method
  78. * @param array $data
  79. *
  80. * @return HttpResponse
  81. */
  82. public function makeRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array())
  83. {
  84. $request = new HttpRequest($method, $url);
  85. $headers = array();
  86. if (!empty($data)) {
  87. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  88. $request->setContent(http_build_query($data));
  89. }
  90. $request->setHeaders($headers);
  91. $response = new HttpResponse();
  92. $this->httpClient->send($request, $response);
  93. return $response->getContent();
  94. }
  95. /**
  96. * @param string $url
  97. * @param string $method
  98. * @param array $data
  99. * @param array $credentials
  100. *
  101. * @return HttpResponse
  102. */
  103. public function makeGetRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array(), $credentials = array())
  104. {
  105. $headers = array();
  106. if ($token = $this->securityTokenStorage->getToken()) {
  107. if (method_exists($token, 'getAccessToken')) {
  108. $headers[] = 'Authorization: Bearer ' . $token->getAccessToken();
  109. }
  110. } elseif (!empty($credentials) && isset($credentials['username']) && isset($credentials['password'])) {
  111. $headers[] = 'Authorization: Basic ' . base64_encode($credentials['username'] . ":" . $credentials['password']);
  112. } else {
  113. return '';
  114. }
  115. $request = new HttpRequest($method, $url);
  116. if (!empty($data)) {
  117. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  118. $request->setContent(http_build_query($data));
  119. }
  120. $request->setHeaders($headers);
  121. $response = new HttpResponse();
  122. $this->httpClient->send($request, $response);
  123. $response = $response->getContent();
  124. return $response;
  125. }
  126. /**
  127. * Similar a getArray pero con mas parametros
  128. *
  129. * @param string $url
  130. * @param array $filters
  131. * @param array $order_by
  132. * @param integer $limit
  133. * @param integer $offset
  134. *
  135. * @return array
  136. */
  137. public function getData($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  138. {
  139. $data = array();
  140. try {
  141. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  142. $data = json_decode($this->makeGetRequest($url), true);
  143. } catch (\Exception $ex) {
  144. // TODO : Loguear esta exception o lanzarla.
  145. }
  146. return $data;
  147. }
  148. /**
  149. * Similar a getData pero la request no hace authentication
  150. *
  151. * @param string $url
  152. * @param array $filters
  153. * @param array $order_by
  154. * @param integer $limit
  155. * @param integer $offset
  156. *
  157. * @return array
  158. */
  159. public function get($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  160. {
  161. $data = array();
  162. try {
  163. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  164. $data = json_decode($this->makeRequest($url), true);
  165. } catch (\Exception $ex) {
  166. }
  167. return $data;
  168. }
  169. /**
  170. * @param string $webservice
  171. * @param array $filters
  172. * @param array $order_by
  173. * @param int $limit
  174. * @param int $offset
  175. * @param boolean $qbCriteria
  176. *
  177. * @return string
  178. */
  179. public function buildUrl($webservice, $filters = array(), $qbCriteria = false, $order_by = array(), $limit = 20, $offset = null)
  180. {
  181. $url = $webservice . '?';
  182. if ($this->serviceContainer->hasParameter($webservice)) {
  183. $url = $this->serviceContainer->getParameter($webservice) . '?';
  184. }
  185. if ($filters) {
  186. $url .= http_build_query(array('filters' => $filters));
  187. }
  188. if ($order_by) {
  189. $url .= '&' . http_build_query(array('order_by' => $order_by));
  190. }
  191. if ($limit) {
  192. $url .= "&limit={$limit}";
  193. }
  194. if ($offset) {
  195. $url .= "&offset={$offset}";
  196. }
  197. if ($qbCriteria) {
  198. $url .= '&filters[qb-criteria]';
  199. }
  200. return $url;
  201. }
  202. /**
  203. * @param string $webservice
  204. * @param int $id
  205. *
  206. * @return string
  207. */
  208. public function getById($webservice, $id)
  209. {
  210. $result = $this->getArray($webservice, array(
  211. 'id' => $id
  212. ));
  213. return isset($result[0]) && isset($result[0]['id']) && isset($result[0]['name'])
  214. ? "{$result[0]['id']} - {$result[0]['name']}"
  215. : $id;
  216. }
  217. /**
  218. * @param string $webservice
  219. * @param int $id
  220. * @param array $data
  221. *
  222. * @return array
  223. */
  224. public function putData($webservice, $id, $data)
  225. {
  226. if ($this->serviceContainer->hasParameter($webservice)) {
  227. $url = str_replace(".json", "/{$id}", $this->serviceContainer->getParameter($webservice));
  228. $data_string = json_encode($data);
  229. $ch = curl_init($url);
  230. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  231. curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  232. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
  233. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  234. try {
  235. $return = curl_exec($ch);
  236. } catch (\Exception $ex) {
  237. return array("error" => "Connection Error.");
  238. }
  239. if ($return) {
  240. return json_decode($return, true);
  241. } else {
  242. return array("error" => "Transaction Error.");
  243. }
  244. }
  245. return array("error" => "Webservice({$webservice}) not found.");
  246. }
  247. public function buildUrlForId($ws, $id = null, $extra = null)
  248. {
  249. $url = $this->serviceContainer->getParameter($ws);
  250. if (!is_null($id)) {
  251. $url = str_replace(".json", "/{$id}", $url);
  252. }
  253. return $url . $extra;
  254. }
  255. /**
  256. * @return ContainerInterface
  257. */
  258. public function getServiceContainer()
  259. {
  260. return $this->serviceContainer;
  261. }
  262. /**
  263. * @return TokenStorage
  264. */
  265. public function getSecurityTokenStorage()
  266. {
  267. return $this->securityTokenStorage;
  268. }
  269. /**
  270. * @return Curl
  271. */
  272. public function getHttpClient()
  273. {
  274. return $this->httpClient;
  275. }
  276. /**
  277. * @param string $webservice
  278. * @param int $id
  279. *
  280. * @return string Funcion que retorna todos los datos del objeto.
  281. */
  282. public function getByIdData($webservice, $id)
  283. {
  284. $result = $this->getArray($webservice, array(
  285. 'id' => $id
  286. ));
  287. return isset($result[0]) ? $result[0] : $id;
  288. }
  289. }