Webservice.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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(), $qbCriteria = false, $order_by = array(), $limit = 20, $offset = null)
  44. {
  45. $choices = array();
  46. $results = $this->getArray($webservice, $params, $qbCriteria, $order_by, $limit, $offset);
  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(), $qbCriteria = true, $order_by = array(), $limit = 20, $offset = null)
  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, $qbCriteria, $order_by, $limit, $offset);
  69. $results = json_decode($this->makeGetRequest($url), true);
  70. } catch (\Exception $ex) {
  71. $this->log($ex->getMessage(), 'error');
  72. }
  73. }
  74. return (array)$results;
  75. }
  76. /**
  77. * @param string $url
  78. * @param string $method
  79. * @param array $data
  80. * @param int $timeout
  81. *
  82. * @return HttpResponse
  83. */
  84. public function makeRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array(), $timeout = 60)
  85. {
  86. try {
  87. $request = new HttpRequest($method, $url);
  88. $headers = array();
  89. if (!empty($data)) {
  90. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  91. $request->setContent(http_build_query($data));
  92. }
  93. $request->setHeaders($headers);
  94. $response = new HttpResponse();
  95. $this->httpClient->setTimeout($timeout);
  96. $this->httpClient->send($request, $response);
  97. $response = $response->getContent();
  98. } catch (RequestException $ex) {
  99. $response = '';
  100. $this->log($ex->getMessage(), 'error');
  101. }
  102. return $response;
  103. }
  104. /**
  105. * @param string $url
  106. * @param string $method
  107. * @param array $data
  108. * @param array $credentials
  109. * @param array $cookies
  110. * @param int $timeout
  111. *
  112. * @return HttpResponse
  113. */
  114. public function makeGetRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array(), $credentials = array(), $cookies = array(), $timeout = 60)
  115. {
  116. try {
  117. $headers = array();
  118. $token = $this->securityTokenStorage->getToken();
  119. if ($token && method_exists($token, 'getAccessToken')) {
  120. $headers[] = 'Authorization: Bearer ' . $token->getAccessToken();
  121. } elseif (!empty($credentials) && isset($credentials['username']) && isset($credentials['password'])) {
  122. $headers[] = 'Authorization: Basic ' . base64_encode($credentials['username'] . ":" . $credentials['password']);
  123. }
  124. foreach ($cookies as $cookie => $value) {
  125. $headers[] = "Cookie: {$cookie}={$value}";
  126. }
  127. $request = new HttpRequest($method, $url);
  128. if (!empty($data)) {
  129. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  130. $request->setContent(http_build_query($data));
  131. }
  132. $request->setHeaders($headers);
  133. $response = new HttpResponse();
  134. $this->httpClient->setTimeout($timeout);
  135. $this->httpClient->send($request, $response);
  136. $response = $response->getContent();
  137. } catch (RequestException $ex) {
  138. $this->log($ex->getMessage(), 'error');
  139. throw $ex;
  140. }
  141. return $response;
  142. }
  143. /**
  144. * Similar a getArray pero con mas parametros
  145. *
  146. * @param string $url
  147. * @param array $filters
  148. * @param array $order_by
  149. * @param integer $limit
  150. * @param integer $offset
  151. *
  152. * @return array
  153. */
  154. public function getData($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  155. {
  156. $data = array();
  157. try {
  158. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  159. $data = json_decode($this->makeGetRequest($url), true);
  160. } catch (\Exception $ex) {
  161. $this->log($ex->getMessage(), 'error');
  162. }
  163. return $data;
  164. }
  165. /**
  166. * Similar a getData pero la request no hace authentication
  167. *
  168. * @param string $url
  169. * @param array $filters
  170. * @param array $order_by
  171. * @param integer $limit
  172. * @param integer $offset
  173. *
  174. * @return array
  175. */
  176. public function get($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  177. {
  178. $data = array();
  179. try {
  180. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  181. $data = json_decode($this->makeRequest($url), true);
  182. } catch (\Exception $ex) {
  183. $this->log($ex->getMessage(), 'error');
  184. }
  185. return $data;
  186. }
  187. /**
  188. * @param string $webservice
  189. * @param array $filters
  190. * @param boolean $qbCriteria
  191. * @param array $order_by
  192. * @param int $limit
  193. * @param int $offset
  194. *
  195. * @return string
  196. */
  197. public function buildUrl($webservice, $filters = array(), $qbCriteria = false, $order_by = array(), $limit = 20, $offset = null)
  198. {
  199. $url = $webservice;
  200. if ($this->serviceContainer->hasParameter($webservice)) {
  201. $url = $this->serviceContainer->getParameter($webservice);
  202. }
  203. $parameters = [];
  204. if ($filters) {
  205. $parameters['filters'] = $filters;
  206. }
  207. if ($order_by) {
  208. $parameters['order_by'] = $order_by;
  209. }
  210. if ($limit) {
  211. $parameters['limit'] = $limit;
  212. }
  213. if ($offset) {
  214. $parameters['offset'] = $offset;
  215. }
  216. if (!empty($parameters)) {
  217. $url .= '?' . http_build_query($parameters);
  218. }
  219. if ($qbCriteria) {
  220. $url .= '&filters%5Bqb-criteria%5D';
  221. }
  222. return $url;
  223. }
  224. /**
  225. * @param string $webservice
  226. * @param int $id
  227. *
  228. * @return string
  229. */
  230. public function getById($webservice, $id)
  231. {
  232. $result = $this->getArray($webservice, array(
  233. 'id' => $id,
  234. ));
  235. $isset = isset($result[0]) && isset($result[0]['id']) && isset($result[0]['externalId']) && isset($result[0]['name']);
  236. return $isset
  237. ? "{$result[0]['externalId']} - {$result[0]['name']} ({$result[0]['id']})"
  238. : $id;
  239. }
  240. /**
  241. * @param string $webservice
  242. * @param int $id
  243. * @param array $data
  244. *
  245. * @return array
  246. */
  247. public function putData($webservice, $id, $data)
  248. {
  249. if ($this->serviceContainer->hasParameter($webservice)) {
  250. $url = str_replace(".json", "/{$id}", $this->serviceContainer->getParameter($webservice));
  251. $data_string = json_encode($data);
  252. $ch = curl_init($url);
  253. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  254. curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  255. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
  256. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  257. try {
  258. $return = curl_exec($ch);
  259. } catch (\Exception $ex) {
  260. $this->log($ex->getMessage(), 'error');
  261. return array("error" => "Connection Error.");
  262. }
  263. if ($return) {
  264. return json_decode($return, true);
  265. } else {
  266. return array("error" => "Transaction Error.");
  267. }
  268. }
  269. return array("error" => "Webservice({$webservice}) not found.");
  270. }
  271. public function buildUrlForId($ws, $id = null, $extra = null)
  272. {
  273. $url = $this->serviceContainer->getParameter($ws);
  274. if (!is_null($id)) {
  275. $url = str_replace(".json", "/{$id}", $url);
  276. }
  277. return $url . $extra;
  278. }
  279. /**
  280. * @return ContainerInterface
  281. */
  282. public function getServiceContainer()
  283. {
  284. return $this->serviceContainer;
  285. }
  286. /**
  287. * @return TokenStorage
  288. */
  289. public function getSecurityTokenStorage()
  290. {
  291. return $this->securityTokenStorage;
  292. }
  293. /**
  294. * @return Curl
  295. */
  296. public function getHttpClient()
  297. {
  298. return $this->httpClient;
  299. }
  300. /**
  301. * @param string $webservice
  302. * @param int $id
  303. *
  304. * @return string Funcion que retorna todos los datos del objeto.
  305. */
  306. public function getByIdData($webservice, $id)
  307. {
  308. $result = $this->getArray($webservice, array(
  309. 'id' => $id
  310. ));
  311. return isset($result[0]) ? $result[0] : $id;
  312. }
  313. /**
  314. * Filtra las clientes de los admin.
  315. * @param $queryBuilder
  316. * @param $alias
  317. * @param $field
  318. * @param $value
  319. *
  320. * @return bool
  321. */
  322. public function getClientFilter($queryBuilder, $alias, $field, $value)
  323. {
  324. $resp = false;
  325. if ($value['value']) {
  326. if ($field == 'clientId') {
  327. // es el filtro de clientes
  328. // debo llamar al webservice para obtener los datos
  329. // actualmente filtra por id, name, address
  330. if (is_numeric($value['value'])) {
  331. $clients = $this->getData('client',
  332. array(
  333. 'qb-criteria' => '',
  334. 'orWhere' => '',
  335. 'id' => $value['value'],
  336. 'externalId' => $value['value'],
  337. )
  338. );
  339. } else {
  340. $clients = $this->getData('client',
  341. array(
  342. 'qb-criteria' => '',
  343. 'orWhere' => '',
  344. 'id' => $value['value'],
  345. 'externalId' => $value['value'],
  346. 'name' => $value['value'],
  347. 'address' => $value['value'],
  348. )
  349. );
  350. }
  351. if (count($clients) == 0) {
  352. // no se encontraron clientes con el filtro que se paso
  353. $queryBuilder->andWhere($queryBuilder->expr()->eq(1, 2));
  354. } else {
  355. $queryBuilder->andWhere(
  356. $queryBuilder->expr()->in(
  357. $alias . '.clientId', array_column($clients, 'id'))
  358. );
  359. $resp = true;
  360. }
  361. }
  362. }
  363. return $resp;
  364. }
  365. /**
  366. * @param $message
  367. * @param $level
  368. * @param $monologLoggerId
  369. */
  370. public function log($message, $level = 'info', $monologLoggerId = 'monolog.logger.webservice')
  371. {
  372. if ($this->serviceContainer->has($monologLoggerId)) {
  373. $this->serviceContainer->get($monologLoggerId)->$level($message);
  374. }
  375. }
  376. /**
  377. * Similar a getData pero la request no hace authentication
  378. *
  379. * @param string $url
  380. * @param array $filters
  381. * @param array $order_by
  382. * @param integer $limit
  383. * @param integer $offset
  384. *
  385. * @return array
  386. */
  387. public function getOauth($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  388. {
  389. $data = array();
  390. try {
  391. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  392. $data = json_decode($this->makeGetRequest($url), true);
  393. } catch (\Exception $ex) {
  394. $this->log($ex->getMessage(), 'error');
  395. }
  396. return $data;
  397. }
  398. }