123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331 |
- <?php
- namespace WebserviceBundle\Services;
- use Buzz\Client\Curl;
- use Buzz\Message\Request as HttpRequest;
- use Buzz\Message\RequestInterface as HttpRequestInterface;
- use Buzz\Message\Response as HttpResponse;
- use Symfony\Component\DependencyInjection\ContainerInterface;
- use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
- class Webservice
- {
- /**
- * @var ContainerInterface
- */
- protected $serviceContainer;
- /**
- * @var TokenStorage
- */
- protected $securityTokenStorage;
- /**
- * @var Curl
- */
- protected $httpClient;
- /**
- * @param ContainerInterface $serviceContainer
- * @param TokenStorageInterface $securityTokenStorage
- * @param Curl $httpClient
- */
- public function __construct(ContainerInterface $serviceContainer, TokenStorageInterface $securityTokenStorage, Curl $httpClient)
- {
- $this->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())
- {
- $choices = array();
- $results = $this->getArray($webservice, $params);
- foreach ($results as $row) {
- if (isset($row['name']) && isset($row['id'])) {
- $choices[$row['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())
- {
- $results = array();
- if ($this->serviceContainer->hasParameter($webservice)) {
- try {
- // Por defecto agrega filters[qb-criteria] y limit=20
- $url = $this->buildUrl($webservice, $params, true);
- $results = json_decode($this->makeGetRequest($url), true);
- } catch (\Exception $ex) {
- var_dump($ex->getMessage());
- }
- }
- return (array)$results;
- }
- /**
- * @param string $url
- * @param string $method
- * @param array $data
- *
- * @return HttpResponse
- */
- public function makeRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array())
- {
- $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->send($request, $response);
- return $response->getContent();
- }
- /**
- * @param string $url
- * @param string $method
- * @param array $data
- * @param array $credentials
- *
- * @return HttpResponse
- */
- public function makeGetRequest($url, $method = HttpRequestInterface::METHOD_GET, $data = array(), $credentials = array())
- {
- $headers = array();
- if ($token = $this->securityTokenStorage->getToken()) {
- if (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']);
- } else {
- return '';
- }
- $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->send($request, $response);
- $response = $response->getContent();
- 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) {
- // TODO : Loguear esta exception o lanzarla.
- }
- 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) {
- }
- return $data;
- }
- /**
- * @param string $webservice
- * @param array $filters
- * @param array $order_by
- * @param int $limit
- * @param int $offset
- * @param boolean $qbCriteria
- *
- * @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) . '?';
- }
- if ($filters) {
- $url .= http_build_query(array('filters' => $filters));
- }
- if ($order_by) {
- $url .= '&' . http_build_query(array('order_by' => $order_by));
- }
- if ($limit) {
- $url .= "&limit={$limit}";
- }
- if ($offset) {
- $url .= "&offset={$offset}";
- }
-
- if ($qbCriteria) {
- $url .= '&filters[qb-criteria]';
- }
- return $url;
- }
- /**
- * @param string $webservice
- * @param int $id
- *
- * @return string
- */
- public function getById($webservice, $id)
- {
- $result = $this->getArray($webservice, array(
- 'id' => $id
- ));
- return isset($result[0]) && isset($result[0]['id']) && isset($result[0]['name'])
- ? "{$result[0]['id']} - {$result[0]['name']}"
- : $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) {
- 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;
- }
- }
|