Webservice.php 14 KB

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