Webservice.php 13 KB

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