Webservice.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. <?php
  2. namespace WebserviceBundle\Services;
  3. use Buzz\Client\Curl;
  4. use Buzz\Exception\RequestException;
  5. use Buzz\Message\Request as HttpRequest;
  6. use Buzz\Message\RequestInterface as HttpRequestInterface;
  7. use Buzz\Message\Response as HttpResponse;
  8. use Symfony\Component\DependencyInjection\ContainerInterface;
  9. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  10. class Webservice
  11. {
  12. /**
  13. * @var ContainerInterface
  14. */
  15. protected $serviceContainer;
  16. /**
  17. * @var TokenStorage
  18. */
  19. protected $securityTokenStorage;
  20. /**
  21. * @var Curl
  22. */
  23. protected $httpClient;
  24. /**
  25. * @param ContainerInterface $serviceContainer
  26. * @param TokenStorageInterface $securityTokenStorage
  27. * @param Curl $httpClient
  28. */
  29. public function __construct(ContainerInterface $serviceContainer, TokenStorageInterface $securityTokenStorage, Curl $httpClient)
  30. {
  31. $this->serviceContainer = $serviceContainer;
  32. $this->securityTokenStorage = $securityTokenStorage;
  33. $this->httpClient = $httpClient;
  34. }
  35. /**
  36. * Retorna el resultado para utilizar en un choice form field
  37. *
  38. * @param string $webservice
  39. * @param array $params
  40. *
  41. * @return array
  42. */
  43. public function getChoices($webservice, $params = array())
  44. {
  45. $choices = array();
  46. $results = $this->getArray($webservice, $params);
  47. foreach ($results as $row) {
  48. if (isset($row['name']) && isset($row['id'])) {
  49. $choices[$row['name']] = $row['id'];
  50. }
  51. }
  52. return $choices;
  53. }
  54. /**
  55. * Retorna el resultado como un array
  56. *
  57. * @param string $webservice
  58. * @param array $params
  59. *
  60. * @return array
  61. */
  62. public function getArray($webservice, $params = array())
  63. {
  64. $results = array();
  65. if ($this->serviceContainer->hasParameter($webservice)) {
  66. try {
  67. // Por defecto agrega filters[qb-criteria] y limit=20
  68. $url = $this->buildUrl($webservice, $params, true);
  69. $results = json_decode($this->makeGetRequest($url), true);
  70. } catch (\Exception $ex) {
  71. var_dump($ex->getMessage());
  72. }
  73. }
  74. return (array)$results;
  75. }
  76. /**
  77. * @param string $url
  78. * @param string $method
  79. * @param array $data
  80. *
  81. * @return HttpResponse
  82. */
  83. public function makeRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array())
  84. {
  85. try {
  86. $request = new HttpRequest($method, $url);
  87. $headers = array();
  88. if (!empty($data)) {
  89. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  90. $request->setContent(http_build_query($data));
  91. }
  92. $request->setHeaders($headers);
  93. $response = new HttpResponse();
  94. $this->httpClient->send($request, $response);
  95. $response = $response->getContent();
  96. } catch (RequestException $ex) {
  97. $response = '';
  98. }
  99. return $response;
  100. }
  101. /**
  102. * @param string $url
  103. * @param string $method
  104. * @param array $data
  105. * @param array $credentials
  106. *
  107. * @return HttpResponse
  108. */
  109. public function makeGetRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array(), $credentials = array())
  110. {
  111. try {
  112. $headers = array();
  113. $token = $this->securityTokenStorage->getToken();
  114. if ($token && method_exists($token, 'getAccessToken')) {
  115. $headers[] = 'Authorization: Bearer ' . $token->getAccessToken();
  116. } elseif (!empty($credentials) && isset($credentials['username']) && isset($credentials['password'])) {
  117. $headers[] = 'Authorization: Basic ' . base64_encode($credentials['username'] . ":" . $credentials['password']);
  118. }
  119. $request = new HttpRequest($method, $url);
  120. if (!empty($data)) {
  121. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  122. $request->setContent(http_build_query($data));
  123. }
  124. $request->setHeaders($headers);
  125. $response = new HttpResponse();
  126. $this->httpClient->send($request, $response);
  127. $response = $response->getContent();
  128. } catch (RequestException $ex) {
  129. throw $ex;
  130. }
  131. return $response;
  132. }
  133. /**
  134. * Similar a getArray pero con mas parametros
  135. *
  136. * @param string $url
  137. * @param array $filters
  138. * @param array $order_by
  139. * @param integer $limit
  140. * @param integer $offset
  141. *
  142. * @return array
  143. */
  144. public function getData($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  145. {
  146. $data = array();
  147. try {
  148. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  149. $data = json_decode($this->makeGetRequest($url), true);
  150. } catch (\Exception $ex) {
  151. // TODO : Loguear esta exception o lanzarla.
  152. }
  153. return $data;
  154. }
  155. /**
  156. * Similar a getData pero la request no hace authentication
  157. *
  158. * @param string $url
  159. * @param array $filters
  160. * @param array $order_by
  161. * @param integer $limit
  162. * @param integer $offset
  163. *
  164. * @return array
  165. */
  166. public function get($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  167. {
  168. $data = array();
  169. try {
  170. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  171. $data = json_decode($this->makeRequest($url), true);
  172. } catch (\Exception $ex) {
  173. }
  174. return $data;
  175. }
  176. /**
  177. * @param string $webservice
  178. * @param array $filters
  179. * @param boolean $qbCriteria
  180. * @param array $order_by
  181. * @param int $limit
  182. * @param int $offset
  183. *
  184. * @return string
  185. */
  186. public function buildUrl($webservice, $filters = array(), $qbCriteria = false, $order_by = array(), $limit = 20, $offset = null)
  187. {
  188. $url = $webservice;
  189. if ($this->serviceContainer->hasParameter($webservice)) {
  190. $url = $this->serviceContainer->getParameter($webservice);
  191. }
  192. $parameters = [];
  193. if ($filters) {
  194. $parameters['filters'] = $filters;
  195. }
  196. if ($order_by) {
  197. $parameters['order_by'] = $order_by;
  198. }
  199. if ($limit) {
  200. $parameters['limit'] = $limit;
  201. }
  202. if ($offset) {
  203. $parameters['offset'] = $offset;
  204. }
  205. if (!empty($parameters)) {
  206. $url .= '?' . http_build_query($parameters);
  207. }
  208. if ($qbCriteria) {
  209. $url .= '&filters%5Bqb-criteria%5D';
  210. }
  211. return $url;
  212. }
  213. /**
  214. * @param string $webservice
  215. * @param int $id
  216. *
  217. * @return string
  218. */
  219. public function getById($webservice, $id)
  220. {
  221. $result = $this->getArray($webservice, array(
  222. 'id' => $id
  223. ));
  224. return isset($result[0]) && isset($result[0]['id']) && isset($result[0]['name'])
  225. ? "{$result[0]['id']} - {$result[0]['name']}"
  226. : $id;
  227. }
  228. /**
  229. * @param string $webservice
  230. * @param int $id
  231. * @param array $data
  232. *
  233. * @return array
  234. */
  235. public function putData($webservice, $id, $data)
  236. {
  237. if ($this->serviceContainer->hasParameter($webservice)) {
  238. $url = str_replace(".json", "/{$id}", $this->serviceContainer->getParameter($webservice));
  239. $data_string = json_encode($data);
  240. $ch = curl_init($url);
  241. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  242. curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  243. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
  244. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  245. try {
  246. $return = curl_exec($ch);
  247. } catch (\Exception $ex) {
  248. return array("error" => "Connection Error.");
  249. }
  250. if ($return) {
  251. return json_decode($return, true);
  252. } else {
  253. return array("error" => "Transaction Error.");
  254. }
  255. }
  256. return array("error" => "Webservice({$webservice}) not found.");
  257. }
  258. public function buildUrlForId($ws, $id = null, $extra = null)
  259. {
  260. $url = $this->serviceContainer->getParameter($ws);
  261. if (!is_null($id)) {
  262. $url = str_replace(".json", "/{$id}", $url);
  263. }
  264. return $url . $extra;
  265. }
  266. /**
  267. * @return ContainerInterface
  268. */
  269. public function getServiceContainer()
  270. {
  271. return $this->serviceContainer;
  272. }
  273. /**
  274. * @return TokenStorage
  275. */
  276. public function getSecurityTokenStorage()
  277. {
  278. return $this->securityTokenStorage;
  279. }
  280. /**
  281. * @return Curl
  282. */
  283. public function getHttpClient()
  284. {
  285. return $this->httpClient;
  286. }
  287. /**
  288. * @param string $webservice
  289. * @param int $id
  290. *
  291. * @return string Funcion que retorna todos los datos del objeto.
  292. */
  293. public function getByIdData($webservice, $id)
  294. {
  295. $result = $this->getArray($webservice, array(
  296. 'id' => $id
  297. ));
  298. return isset($result[0]) ? $result[0] : $id;
  299. }
  300. /**
  301. * Filtra las clientes de los admin.
  302. * @param $queryBuilder
  303. * @param $alias
  304. * @param $field
  305. * @param $value
  306. * @return bool
  307. */
  308. public function getClientFilter($queryBuilder, $alias, $field, $value)
  309. {
  310. $resp = false;
  311. if ($value['value']) {
  312. if ($field == 'clientId') {
  313. // es el filtro de clientes
  314. // debo llamar al webservice para obtener los datos
  315. // actualmente filtra por id, name, address
  316. if (is_numeric($value['value'])) {
  317. $clients = $this->getData('client',
  318. array(
  319. 'externalId' => $value['value']
  320. )
  321. );
  322. } else {
  323. $clients = $this->getData('client',
  324. array(
  325. 'qb-criteria' => '',
  326. 'orWhere' => '',
  327. 'externalId' => $value['value'],
  328. 'name' => $value['value'],
  329. 'address' => $value['value']
  330. )
  331. );
  332. }
  333. if (count($clients) == 0) {
  334. // no se encontraron clientes con el filtro que se paso
  335. $queryBuilder->andWhere($queryBuilder->expr()->eq(1, 2));
  336. } else {
  337. $queryBuilder->andWhere(
  338. $queryBuilder->expr()->in(
  339. $alias . '.clientId', array_column($clients, 'id'))
  340. );
  341. $resp = true;
  342. }
  343. }
  344. }
  345. return $resp;
  346. }
  347. }