Webservice.php 12 KB

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