Webservice.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. return isset($result[0]) && isset($result[0]['id']) && isset($result[0]['name'])
  232. ? "{$result[0]['id']} - {$result[0]['name']}"
  233. : $id;
  234. }
  235. /**
  236. * @param string $webservice
  237. * @param int $id
  238. * @param array $data
  239. *
  240. * @return array
  241. */
  242. public function putData($webservice, $id, $data)
  243. {
  244. if ($this->serviceContainer->hasParameter($webservice)) {
  245. $url = str_replace(".json", "/{$id}", $this->serviceContainer->getParameter($webservice));
  246. $data_string = json_encode($data);
  247. $ch = curl_init($url);
  248. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  249. curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  250. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
  251. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  252. try {
  253. $return = curl_exec($ch);
  254. } catch (\Exception $ex) {
  255. $this->log($ex->getMessage(), 'error');
  256. return array("error" => "Connection Error.");
  257. }
  258. if ($return) {
  259. return json_decode($return, true);
  260. } else {
  261. return array("error" => "Transaction Error.");
  262. }
  263. }
  264. return array("error" => "Webservice({$webservice}) not found.");
  265. }
  266. public function buildUrlForId($ws, $id = null, $extra = null)
  267. {
  268. $url = $this->serviceContainer->getParameter($ws);
  269. if (!is_null($id)) {
  270. $url = str_replace(".json", "/{$id}", $url);
  271. }
  272. return $url . $extra;
  273. }
  274. /**
  275. * @return ContainerInterface
  276. */
  277. public function getServiceContainer()
  278. {
  279. return $this->serviceContainer;
  280. }
  281. /**
  282. * @return TokenStorage
  283. */
  284. public function getSecurityTokenStorage()
  285. {
  286. return $this->securityTokenStorage;
  287. }
  288. /**
  289. * @return Curl
  290. */
  291. public function getHttpClient()
  292. {
  293. return $this->httpClient;
  294. }
  295. /**
  296. * @param string $webservice
  297. * @param int $id
  298. *
  299. * @return string Funcion que retorna todos los datos del objeto.
  300. */
  301. public function getByIdData($webservice, $id)
  302. {
  303. $result = $this->getArray($webservice, array(
  304. 'id' => $id
  305. ));
  306. return isset($result[0]) ? $result[0] : $id;
  307. }
  308. /**
  309. * Filtra las clientes de los admin.
  310. * @param $queryBuilder
  311. * @param $alias
  312. * @param $field
  313. * @param $value
  314. *
  315. * @return bool
  316. */
  317. public function getClientFilter($queryBuilder, $alias, $field, $value)
  318. {
  319. $resp = false;
  320. if ($value['value']) {
  321. if ($field == 'clientId') {
  322. // es el filtro de clientes
  323. // debo llamar al webservice para obtener los datos
  324. // actualmente filtra por id, name, address
  325. if (is_numeric($value['value'])) {
  326. $clients = $this->getData('client',
  327. array(
  328. 'externalId' => $value['value']
  329. )
  330. );
  331. } else {
  332. $clients = $this->getData('client',
  333. array(
  334. 'qb-criteria' => '',
  335. 'orWhere' => '',
  336. 'externalId' => $value['value'],
  337. 'name' => $value['value'],
  338. 'address' => $value['value']
  339. )
  340. );
  341. }
  342. if (count($clients) == 0) {
  343. // no se encontraron clientes con el filtro que se paso
  344. $queryBuilder->andWhere($queryBuilder->expr()->eq(1, 2));
  345. } else {
  346. $queryBuilder->andWhere(
  347. $queryBuilder->expr()->in(
  348. $alias . '.clientId', array_column($clients, 'id'))
  349. );
  350. $resp = true;
  351. }
  352. }
  353. }
  354. return $resp;
  355. }
  356. /**
  357. * @param $message
  358. * @param $level
  359. * @param $monologLoggerId
  360. */
  361. public function log($message, $level = 'info', $monologLoggerId = 'monolog.logger.webservice')
  362. {
  363. if ($this->serviceContainer->has($monologLoggerId)) {
  364. $this->serviceContainer->get($monologLoggerId)->$level($message);
  365. }
  366. }
  367. /**
  368. * Similar a getData pero la request no hace authentication
  369. *
  370. * @param string $url
  371. * @param array $filters
  372. * @param array $order_by
  373. * @param integer $limit
  374. * @param integer $offset
  375. *
  376. * @return array
  377. */
  378. public function getOauth($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  379. {
  380. $data = array();
  381. try {
  382. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  383. $data = json_decode($this->makeGetRequest($url), true);
  384. } catch (\Exception $ex) {
  385. $this->log($ex->getMessage(), 'error');
  386. }
  387. return $data;
  388. }
  389. }