Webservice.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. *
  108. * @return HttpResponse
  109. */
  110. public function makeGetRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array(), $credentials = array())
  111. {
  112. try {
  113. $headers = array();
  114. $token = $this->securityTokenStorage->getToken();
  115. if ($token && method_exists($token, 'getAccessToken')) {
  116. $headers[] = 'Authorization: Bearer ' . $token->getAccessToken();
  117. } elseif (!empty($credentials) && isset($credentials['username']) && isset($credentials['password'])) {
  118. $headers[] = 'Authorization: Basic ' . base64_encode($credentials['username'] . ":" . $credentials['password']);
  119. }
  120. $request = new HttpRequest($method, $url);
  121. if (!empty($data)) {
  122. $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  123. $request->setContent(http_build_query($data));
  124. }
  125. $request->setHeaders($headers);
  126. $response = new HttpResponse();
  127. $this->httpClient->send($request, $response);
  128. $response = $response->getContent();
  129. } catch (RequestException $ex) {
  130. $this->log($ex->getMessage(), 'error');
  131. throw $ex;
  132. }
  133. return $response;
  134. }
  135. /**
  136. * Similar a getArray pero con mas parametros
  137. *
  138. * @param string $url
  139. * @param array $filters
  140. * @param array $order_by
  141. * @param integer $limit
  142. * @param integer $offset
  143. *
  144. * @return array
  145. */
  146. public function getData($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  147. {
  148. $data = array();
  149. try {
  150. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  151. $data = json_decode($this->makeGetRequest($url), true);
  152. } catch (\Exception $ex) {
  153. $this->log($ex->getMessage(), 'error');
  154. }
  155. return $data;
  156. }
  157. /**
  158. * Similar a getData pero la request no hace authentication
  159. *
  160. * @param string $url
  161. * @param array $filters
  162. * @param array $order_by
  163. * @param integer $limit
  164. * @param integer $offset
  165. *
  166. * @return array
  167. */
  168. public function get($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  169. {
  170. $data = array();
  171. try {
  172. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  173. $data = json_decode($this->makeRequest($url), true);
  174. } catch (\Exception $ex) {
  175. $this->log($ex->getMessage(), 'error');
  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. $this->log($ex->getMessage(), 'error');
  252. return array("error" => "Connection Error.");
  253. }
  254. if ($return) {
  255. return json_decode($return, true);
  256. } else {
  257. return array("error" => "Transaction Error.");
  258. }
  259. }
  260. return array("error" => "Webservice({$webservice}) not found.");
  261. }
  262. public function buildUrlForId($ws, $id = null, $extra = null)
  263. {
  264. $url = $this->serviceContainer->getParameter($ws);
  265. if (!is_null($id)) {
  266. $url = str_replace(".json", "/{$id}", $url);
  267. }
  268. return $url . $extra;
  269. }
  270. /**
  271. * @return ContainerInterface
  272. */
  273. public function getServiceContainer()
  274. {
  275. return $this->serviceContainer;
  276. }
  277. /**
  278. * @return TokenStorage
  279. */
  280. public function getSecurityTokenStorage()
  281. {
  282. return $this->securityTokenStorage;
  283. }
  284. /**
  285. * @return Curl
  286. */
  287. public function getHttpClient()
  288. {
  289. return $this->httpClient;
  290. }
  291. /**
  292. * @param string $webservice
  293. * @param int $id
  294. *
  295. * @return string Funcion que retorna todos los datos del objeto.
  296. */
  297. public function getByIdData($webservice, $id)
  298. {
  299. $result = $this->getArray($webservice, array(
  300. 'id' => $id
  301. ));
  302. return isset($result[0]) ? $result[0] : $id;
  303. }
  304. /**
  305. * Filtra las clientes de los admin.
  306. * @param $queryBuilder
  307. * @param $alias
  308. * @param $field
  309. * @param $value
  310. *
  311. * @return bool
  312. */
  313. public function getClientFilter($queryBuilder, $alias, $field, $value)
  314. {
  315. $resp = false;
  316. if ($value['value']) {
  317. if ($field == 'clientId') {
  318. // es el filtro de clientes
  319. // debo llamar al webservice para obtener los datos
  320. // actualmente filtra por id, name, address
  321. if (is_numeric($value['value'])) {
  322. $clients = $this->getData('client',
  323. array(
  324. 'externalId' => $value['value']
  325. )
  326. );
  327. } else {
  328. $clients = $this->getData('client',
  329. array(
  330. 'qb-criteria' => '',
  331. 'orWhere' => '',
  332. 'externalId' => $value['value'],
  333. 'name' => $value['value'],
  334. 'address' => $value['value']
  335. )
  336. );
  337. }
  338. if (count($clients) == 0) {
  339. // no se encontraron clientes con el filtro que se paso
  340. $queryBuilder->andWhere($queryBuilder->expr()->eq(1, 2));
  341. } else {
  342. $queryBuilder->andWhere(
  343. $queryBuilder->expr()->in(
  344. $alias . '.clientId', array_column($clients, 'id'))
  345. );
  346. $resp = true;
  347. }
  348. }
  349. }
  350. return $resp;
  351. }
  352. /**
  353. * @param $message
  354. * @param $level
  355. * @param $monologLoggerId
  356. */
  357. public function log($message, $level = 'info', $monologLoggerId = 'monolog.logger.webservice')
  358. {
  359. if ($this->serviceContainer->has($monologLoggerId)) {
  360. $this->serviceContainer->get($monologLoggerId)->$level($message);
  361. }
  362. }
  363. /**
  364. * Similar a getData pero la request no hace authentication
  365. *
  366. * @param string $url
  367. * @param array $filters
  368. * @param array $order_by
  369. * @param integer $limit
  370. * @param integer $offset
  371. *
  372. * @return array
  373. */
  374. public function getOauth($url, $filters = array(), $order_by = array(), $limit = null, $offset = null)
  375. {
  376. $data = array();
  377. try {
  378. $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset);
  379. $data = json_decode($this->makeGetRequest($url), true);
  380. } catch (\Exception $ex) {
  381. $this->log($ex->getMessage(), 'error');
  382. }
  383. return $data;
  384. }
  385. }