Webservice.php 13 KB

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