serviceContainer = $serviceContainer; $this->securityTokenStorage = $securityTokenStorage; $this->httpClient = $httpClient; } /** * Retorna el resultado para utilizar en un choice form field * * @param string $webservice * @param array $params * * @return array */ public function getChoices($webservice, $params = array(), $qbCriteria = false, $order_by = array(), $limit = 20, $offset = null) { $choices = array(); $results = $this->getArray($webservice, $params, $qbCriteria, $order_by, $limit, $offset); foreach ($results as $row) { if (isset($row['name']) && isset($row['id'])) { $name = $row['name']; if (isset($row['externalId'])) // Only clients $name = "{$row['externalId']} - {$row['name']}"; $choices[$name] = $row['id']; } } return $choices; } /** * Retorna el resultado como un array * * @param string $webservice * @param array $params * * @return array */ public function getArray($webservice, $params = array(), $qbCriteria = true, $order_by = array(), $limit = 20, $offset = null) { $results = array(); if ($this->serviceContainer->hasParameter($webservice)) { try { // Por defecto agrega filters[qb-criteria] y limit=20 $url = $this->buildUrl($webservice, $params, $qbCriteria, $order_by, $limit, $offset); $results = json_decode($this->makeGetRequest($url), true); } catch (\Exception $ex) { $this->log($ex->getMessage(), 'error'); } } return (array)$results; } /** * @param string $url * @param string $method * @param array $data * @param int $timeout * * @return HttpResponse */ public function makeRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array(), $timeout = 60) { try { $request = new HttpRequest($method, $url); $headers = array(); if (!empty($data)) { $headers[] = 'Content-Type: application/x-www-form-urlencoded'; $request->setContent(http_build_query($data)); } $request->setHeaders($headers); $response = new HttpResponse(); $this->httpClient->setTimeout($timeout); $this->httpClient->send($request, $response); $response = $response->getContent(); } catch (RequestException $ex) { $response = ''; $this->log($ex->getMessage(), 'error'); } return $response; } /** * @param string $url * @param string $method * @param array $data * @param array $credentials If null then the credentials no send. * @param array $cookies * @param int $timeout * * @return HttpResponse */ public function makeGetRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array(), $credentials = array(), $cookies = array(), $timeout = 60) { try { $headers = array(); $token = $this->securityTokenStorage->getToken(); if ($token && method_exists($token, 'getAccessToken')) { $headers[] = 'Authorization: Bearer ' . $token->getAccessToken(); } elseif (!empty($credentials) && isset($credentials['username']) && isset($credentials['password'])) { $headers[] = 'Authorization: Basic ' . base64_encode($credentials['username'] . ":" . $credentials['password']); } elseif (getenv("CMD_USERNAME") && getenv("CMD_PASSWORD") && !is_null($credentials)) { $headers[] = 'Authorization: Basic ' . base64_encode(getenv("CMD_USERNAME") . ":" . getenv("CMD_PASSWORD")); } foreach ($cookies as $cookie => $value) { $headers[] = "Cookie: {$cookie}={$value}"; } $request = new HttpRequest($method, $url); if (!empty($data)) { $headers[] = 'Content-Type: application/x-www-form-urlencoded'; $request->setContent(http_build_query($data)); } $request->setHeaders($headers); $response = new HttpResponse(); $this->httpClient->setTimeout($timeout); $this->httpClient->send($request, $response); $response = $response->getContent(); } catch (RequestException $ex) { $this->log($ex->getMessage(), 'error'); throw $ex; } return $response; } /** * Similar a getArray pero con mas parametros * * @param string $url * @param array $filters * @param array $order_by * @param integer $limit * @param integer $offset * * @return array */ public function getData($url, $filters = array(), $order_by = array(), $limit = null, $offset = null) { $data = array(); try { $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset); $data = json_decode($this->makeGetRequest($url), true); } catch (\Exception $ex) { $this->log($ex->getMessage(), 'error'); } return $data; } /** * Similar a getData pero la request no hace authentication * * @param string $url * @param array $filters * @param array $order_by * @param integer $limit * @param integer $offset * * @return array */ public function get($url, $filters = array(), $order_by = array(), $limit = null, $offset = null) { $data = array(); try { $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset); $data = json_decode($this->makeRequest($url), true); } catch (\Exception $ex) { $this->log($ex->getMessage(), 'error'); } return $data; } /** * @param string $webservice * @param array $filters * @param boolean $qbCriteria * @param array $order_by * @param int $limit * @param int $offset * * @return string */ public function buildUrl($webservice, $filters = array(), $qbCriteria = false, $order_by = array(), $limit = 20, $offset = null) { $url = $webservice; if ($this->serviceContainer->hasParameter($webservice)) { $url = $this->serviceContainer->getParameter($webservice); } $parameters = []; if ($filters) { $parameters['filters'] = $filters; } if ($order_by) { $parameters['order_by'] = $order_by; } if ($limit) { $parameters['limit'] = $limit; } if ($offset) { $parameters['offset'] = $offset; } if (!empty($parameters)) { $url .= '?' . http_build_query($parameters); } if ($qbCriteria) { $url .= '&filters%5Bqb-criteria%5D'; } return $url; } /** * @param string $webservice * @param int $id * * @return string */ public function getById($webservice, $id) { $result = $this->getArray($webservice, array( 'id' => $id, )); $isset = isset($result[0]) && isset($result[0]['id']) && isset($result[0]['externalId']) && isset($result[0]['name']); return $isset ? "{$result[0]['externalId']} - {$result[0]['name']} ({$result[0]['id']})" : $id; } /** * @param string $webservice * @param int $id * @param array $data * * @return array */ public function putData($webservice, $id, $data) { if ($this->serviceContainer->hasParameter($webservice)) { $url = str_replace(".json", "/{$id}", $this->serviceContainer->getParameter($webservice)); $data_string = json_encode($data); $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string))); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); try { $return = curl_exec($ch); } catch (\Exception $ex) { $this->log($ex->getMessage(), 'error'); return array("error" => "Connection Error."); } if ($return) { return json_decode($return, true); } else { return array("error" => "Transaction Error."); } } return array("error" => "Webservice({$webservice}) not found."); } public function buildUrlForId($ws, $id = null, $extra = null) { $url = $this->serviceContainer->getParameter($ws); if (!is_null($id)) { $url = str_replace(".json", "/{$id}", $url); } return $url . $extra; } /** * @return ContainerInterface */ public function getServiceContainer() { return $this->serviceContainer; } /** * @return TokenStorage */ public function getSecurityTokenStorage() { return $this->securityTokenStorage; } /** * @return Curl */ public function getHttpClient() { return $this->httpClient; } /** * @param string $webservice * @param int $id * * @return string Funcion que retorna todos los datos del objeto. */ public function getByIdData($webservice, $id) { $result = $this->getArray($webservice, array( 'id' => $id )); return isset($result[0]) ? $result[0] : $id; } /** * Filtra las clientes de los admin. * @param $queryBuilder * @param $alias * @param $field * @param $value * * @return bool */ public function getClientFilter($queryBuilder, $alias, $field, $value) { $resp = false; if ($value['value']) { if ($field == 'clientId') { // es el filtro de clientes // debo llamar al webservice para obtener los datos // actualmente filtra por id, name, address if (is_numeric($value['value'])) { $clients = $this->getData('client', array( 'qb-criteria' => '', 'orWhere' => '', 'id' => $value['value'], 'externalId' => $value['value'], ) ); } else { $clients = $this->getData('client', array( 'qb-criteria' => '', 'orWhere' => '', 'id' => $value['value'], 'externalId' => $value['value'], 'name' => $value['value'], 'address' => $value['value'], ) ); } if (count($clients) == 0) { // no se encontraron clientes con el filtro que se paso $queryBuilder->andWhere($queryBuilder->expr()->eq(1, 2)); } else { $queryBuilder->andWhere( $queryBuilder->expr()->in( $alias . '.clientId', array_column($clients, 'id')) ); $resp = true; } } } return $resp; } /** * @param $message * @param $level * @param $monologLoggerId */ public function log($message, $level = 'info', $monologLoggerId = 'monolog.logger.webservice') { if ($this->serviceContainer->has($monologLoggerId)) { $this->serviceContainer->get($monologLoggerId)->$level($message); } } /** * Similar a getData pero la request no hace authentication * * @param string $url * @param array $filters * @param array $order_by * @param integer $limit * @param integer $offset * * @return array */ public function getOauth($url, $filters = array(), $order_by = array(), $limit = null, $offset = null) { $data = array(); try { $url = $this->buildUrl($url, $filters, false, $order_by, $limit, $offset); $data = json_decode($this->makeGetRequest($url), true); } catch (\Exception $ex) { $this->log($ex->getMessage(), 'error'); } return $data; } }