Webservice.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. if ($token = $this->securityTokenStorage->getToken()) {
  114. if (method_exists($token, 'getAccessToken')) {
  115. $headers[] = 'Authorization: Bearer ' . $token->getAccessToken();
  116. }
  117. } elseif (!empty($credentials) && isset($credentials['username']) && isset($credentials['password'])) {
  118. $headers[] = 'Authorization: Basic ' . base64_encode($credentials['username'] . ":" . $credentials['password']);
  119. } else {
  120. return '';
  121. }
  122. $request = new HttpRequest($method, $url);
  123. if (!empty($data)) {
  124. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  125. $request->setContent(http_build_query($data));
  126. }
  127. $request->setHeaders($headers);
  128. $response = new HttpResponse();
  129. $this->httpClient->send($request, $response);
  130. $response = $response->getContent();
  131. } catch (RequestException $ex) {
  132. $response = '';
  133. }
  134. return $response;
  135. }
  136. /**
  137. * Similar a getArray pero con mas parametros
  138. *
  139. * @param string $url
  140. * @param array $filters
  141. * @param array $order_by
  142. * @param integer $limit
  143. * @param integer $offset
  144. *
  145. * @return array
  146. */
  147. public function getData($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  148. {
  149. $data = array();
  150. try {
  151. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  152. $data = json_decode($this->makeGetRequest($url), true);
  153. } catch (\Exception $ex) {
  154. // TODO : Loguear esta exception o lanzarla.
  155. }
  156. return $data;
  157. }
  158. /**
  159. * Similar a getData pero la request no hace authentication
  160. *
  161. * @param string $url
  162. * @param array $filters
  163. * @param array $order_by
  164. * @param integer $limit
  165. * @param integer $offset
  166. *
  167. * @return array
  168. */
  169. public function get($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  170. {
  171. $data = array();
  172. try {
  173. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  174. $data = json_decode($this->makeRequest($url), true);
  175. } catch (\Exception $ex) {
  176. }
  177. return $data;
  178. }
  179. /**
  180. * @param string $webservice
  181. * @param array $filters
  182. * @param boolean $qbCriteria
  183. * @param array $order_by
  184. * @param int $limit
  185. * @param int $offset
  186. *
  187. * @return string
  188. */
  189. public function buildUrl($webservice, $filters = array(), $qbCriteria = false, $order_by = array(), $limit = 20, $offset = null)
  190. {
  191. $url = $webservice;
  192. if ($this->serviceContainer->hasParameter($webservice)) {
  193. $url = $this->serviceContainer->getParameter($webservice);
  194. }
  195. $parameters = [];
  196. if ($filters) {
  197. $parameters['filters'] = $filters;
  198. }
  199. if ($order_by) {
  200. $parameters['order_by'] = $order_by;
  201. }
  202. if ($limit) {
  203. $parameters['limit'] = $limit;
  204. }
  205. if ($offset) {
  206. $parameters['offset'] = $offset;
  207. }
  208. if (!empty($parameters)) {
  209. $url .= '?' . http_build_query($parameters);
  210. }
  211. if ($qbCriteria) {
  212. $url .= '&filters%5Bqb-criteria%5D';
  213. }
  214. return $url;
  215. }
  216. /**
  217. * @param string $webservice
  218. * @param int $id
  219. *
  220. * @return string
  221. */
  222. public function getById($webservice, $id)
  223. {
  224. $result = $this->getArray($webservice, array(
  225. 'id' => $id
  226. ));
  227. return isset($result[0]) && isset($result[0]['id']) && isset($result[0]['name'])
  228. ? "{$result[0]['id']} - {$result[0]['name']}"
  229. : $id;
  230. }
  231. /**
  232. * @param string $webservice
  233. * @param int $id
  234. * @param array $data
  235. *
  236. * @return array
  237. */
  238. public function putData($webservice, $id, $data)
  239. {
  240. if ($this->serviceContainer->hasParameter($webservice)) {
  241. $url = str_replace(".json", "/{$id}", $this->serviceContainer->getParameter($webservice));
  242. $data_string = json_encode($data);
  243. $ch = curl_init($url);
  244. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  245. curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  246. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
  247. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  248. try {
  249. $return = curl_exec($ch);
  250. } catch (\Exception $ex) {
  251. return array("error" => "Connection Error.");
  252. }
  253. if ($return) {
  254. return json_decode($return, true);
  255. } else {
  256. return array("error" => "Transaction Error.");
  257. }
  258. }
  259. return array("error" => "Webservice({$webservice}) not found.");
  260. }
  261. public function buildUrlForId($ws, $id = null, $extra = null)
  262. {
  263. $url = $this->serviceContainer->getParameter($ws);
  264. if (!is_null($id)) {
  265. $url = str_replace(".json", "/{$id}", $url);
  266. }
  267. return $url . $extra;
  268. }
  269. /**
  270. * @return ContainerInterface
  271. */
  272. public function getServiceContainer()
  273. {
  274. return $this->serviceContainer;
  275. }
  276. /**
  277. * @return TokenStorage
  278. */
  279. public function getSecurityTokenStorage()
  280. {
  281. return $this->securityTokenStorage;
  282. }
  283. /**
  284. * @return Curl
  285. */
  286. public function getHttpClient()
  287. {
  288. return $this->httpClient;
  289. }
  290. /**
  291. * @param string $webservice
  292. * @param int $id
  293. *
  294. * @return string Funcion que retorna todos los datos del objeto.
  295. */
  296. public function getByIdData($webservice, $id)
  297. {
  298. $result = $this->getArray($webservice, array(
  299. 'id' => $id
  300. ));
  301. return isset($result[0]) ? $result[0] : $id;
  302. }
  303. /**
  304. * Filtra las clientes de los admin.
  305. * @param $queryBuilder
  306. * @param $alias
  307. * @param $field
  308. * @param $value
  309. * @return bool
  310. */
  311. public function getClientFilter($queryBuilder, $alias, $field, $value)
  312. {
  313. $resp = false;
  314. if ($value['value']) {
  315. if ($field == 'clientId') {
  316. // es el filtro de clientes
  317. // debo llamar al webservice para obtener los datos
  318. // actualmente filtra por id, name, address
  319. if (is_numeric($value['value'])) {
  320. $clients = $this->getData('client',
  321. array(
  322. 'externalId' => $value['value']
  323. )
  324. );
  325. } else {
  326. $clients = $this->getData('client',
  327. array(
  328. 'qb-criteria' => '',
  329. 'orWhere' => '',
  330. 'externalId' => $value['value'],
  331. 'name' => $value['value'],
  332. 'address' => $value['value']
  333. )
  334. );
  335. }
  336. if (count($clients) == 0) {
  337. // no se encontraron clientes con el filtro que se paso
  338. $queryBuilder->andWhere($queryBuilder->expr()->eq(1, 2));
  339. } else {
  340. $queryBuilder->andWhere(
  341. $queryBuilder->expr()->in(
  342. $alias . '.clientId', array_column($clients, 'id'))
  343. );
  344. $resp = true;
  345. }
  346. }
  347. }
  348. return $resp;
  349. }
  350. }