Webservice.php 8.6 KB

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