PageRenderTime 99ms CodeModel.GetById 27ms RepoModel.GetById 2ms app.codeStats 0ms

/tags/v1.0.0/application/plugin/FaturaSimples/FaturaSimples/FaturaSimples.php

https://bitbucket.org/bisa_desenvolvimento/filiadosweb
PHP | 277 lines | 147 code | 37 blank | 93 comment | 21 complexity | 853b5fd8acbb99821a2ceb571499ac76 MD5 | raw file
  1. <?php
  2. abstract class FaturaSimples
  3. {
  4. /**
  5. * Constantes de operadores de filtros.
  6. *
  7. * @var string
  8. */
  9. const FILTRO_EQ = 'eq';
  10. const FILTRO_NEQ = 'neq';
  11. const FILTRO_GT = 'gt';
  12. const FILTRO_LT = 'lt';
  13. const FILTRO_BETWEEN = 'between';
  14. const FILTRO_ISNULL = 'isnull';
  15. const FILTRO_ISNOTNULL = 'isnotnull';
  16. const FILTRO_CONTAINS = 'contains';
  17. const FILTRO_NOTCONTAINS = 'notcontains';
  18. /**
  19. * Chave de API.
  20. *
  21. * @var string
  22. */
  23. protected static $apiKey = '';
  24. /**
  25. * Base do endpoint da api de uma instalação da Fatura Simples.
  26. *
  27. * @var string
  28. */
  29. protected static $endpoint = '';
  30. /**
  31. * Versão da API sendo utilizada.
  32. *
  33. * @var string
  34. */
  35. protected static $apiVersion = null;
  36. /**
  37. * Reseta as configurações da classe para permitir uso em outra instância.
  38. */
  39. public static function reset()
  40. {
  41. self::$apiKey = '';
  42. self::$endpoint = '';
  43. self::$apiVersion = '';
  44. }
  45. /**
  46. * Configura o objeto com a chave de API e o endpoint da instalação.
  47. *
  48. * @param string $endpoint Domínio da sua instalação
  49. * @param string $apiKey Chave de api gerada dentro da Fatura Simples
  50. */
  51. public static function configure($endpoint, $apiKey, $apiVersion = null)
  52. {
  53. if (strlen($apiKey) > 10) {
  54. self::$apiKey = $apiKey;
  55. } else {
  56. throw new Exception(__CLASS__.': informe uma chave de api válida.');
  57. }
  58. if (strlen($endpoint) > 0) {
  59. // Aceita que o endpoint seja passado completo como uma URL
  60. if (stripos($endpoint, 'http') !== false) {
  61. self::$endpoint = $endpoint;
  62. } else {
  63. // Caso padrão onde se passa somente o domínio
  64. self::$endpoint = "https://{$endpoint}.faturasimples.com.br";
  65. }
  66. }
  67. if ($apiVersion !== null) {
  68. self::$apiVersion = $apiVersion;
  69. }
  70. if (!strlen(self::$endpoint) || !preg_match("/^https?:\/\/([a-z0-9]{1,})/", self::$endpoint)) {
  71. throw new Exception(
  72. __CLASS__.": informe um domínio válido. Você deve informar somente o subdomínio: 'suaempresa'."
  73. );
  74. }
  75. return true;
  76. }
  77. /**
  78. * Executa uma requisição simples via curl.
  79. *
  80. * @param string $url
  81. * @param mixed[] $options
  82. *
  83. * @return string Resposta da requisição
  84. */
  85. protected static function _curl($url, $options = array())
  86. {
  87. if (!strlen(self::$apiKey)) {
  88. throw new Exception(
  89. __CLASS__.': Utilize o método FaturaSimples::configure antes de realizar chamadas.
  90. '
  91. );
  92. }
  93. $curl = curl_init();
  94. $headers = array('Authorization: Basic '.base64_encode(self::$apiKey.':'));
  95. if (self::$apiVersion !== null) {
  96. $headers[] = 'FaturaSimples-Versao: '.self::$apiVersion;
  97. }
  98. $optionsDefault = array(
  99. CURLOPT_RETURNTRANSFER => 1,
  100. CURLOPT_URL => $url,
  101. CURLOPT_SSL_VERIFYPEER => true,
  102. CURLOPT_SSL_VERIFYHOST => 2,
  103. CURLOPT_HTTPHEADER => $headers,
  104. );
  105. foreach ($options as $key => $value) {
  106. $optionsDefault[$key] = $value;
  107. }
  108. curl_setopt_array($curl, $optionsDefault);
  109. $ret = curl_exec($curl);
  110. if ($ret === false) {
  111. throw new Exception(__CLASS__.': erro na execução do CURL: '.curl_error($curl));
  112. }
  113. curl_close($curl);
  114. return $ret;
  115. }
  116. /**
  117. * Realiza uma requisição à API usando cURL.
  118. *
  119. * @param string $path
  120. * @param string $method Método do HTTP a ser utilizado: GET, POST, DELETE
  121. * @param string[] $params
  122. *
  123. * @throws Exception
  124. */
  125. protected static function _request($path, $method, $params = array())
  126. {
  127. $curlOpts = array(
  128. CURLOPT_CUSTOMREQUEST => $method,
  129. );
  130. if ($method === 'POST') {
  131. if (!is_array($params) || count($params) === 0) {
  132. throw new Exception(__CLASS__.': não é possível realizar uma requisição sem parâmetros.');
  133. }
  134. $curlOpts[CURLOPT_POST] = 1;
  135. }
  136. // Adiciona os parâmetros na requisição convertendo arrays para JSON quando necessário
  137. if (is_array($params) && count($params) > 0) {
  138. // Caso o parâmetro tenha sido passado como array converte-o para json
  139. foreach ($params as $key => $param) {
  140. if (is_array($param)) {
  141. $params[$key] = json_encode($param);
  142. }
  143. }
  144. // Define os parâmetros como postfields
  145. $curlOpts[CURLOPT_POSTFIELDS] = $params;
  146. }
  147. $ret = self::_curl(self::$endpoint.'/'.$path, $curlOpts);
  148. return $ret;
  149. }
  150. /**
  151. * Método que deve ser implementado pelas classes dos models retornando a string para compor a URL.
  152. *
  153. * @return string
  154. */
  155. protected static function _model()
  156. {
  157. throw new Exception(
  158. 'A classe FaturaSimples nao pode ser usada diretamente.'
  159. .'Utilize uma das subclasses, FaturaSimples_Cliente::, por exemplo.'
  160. );
  161. }
  162. /**
  163. * Cria um novo registro.
  164. *
  165. * @param mixed[] $params
  166. *
  167. * @return string JSON
  168. */
  169. public static function criar($params)
  170. {
  171. return self::_request('api/'.static::_model(), 'POST', $params);
  172. }
  173. /**
  174. * Atualiza os dados de um registro.
  175. *
  176. * @param int $id
  177. * @param mixed[] $params
  178. *
  179. * @return string JSON
  180. */
  181. public static function atualizar($id, $params)
  182. {
  183. return self::_request('api/'.static::_model()."/{$id}", 'POST', $params);
  184. }
  185. /**
  186. * Seleciona um registro.
  187. *
  188. * @param int $id
  189. *
  190. * @return string JSON
  191. */
  192. public static function selecionar($id)
  193. {
  194. return self::_request('api/'.static::_model()."/{$id}", 'GET');
  195. }
  196. /**
  197. * Deleta um registro do sistema.
  198. *
  199. * @param int $id
  200. *
  201. * @return string JSON
  202. */
  203. public static function deletar($id)
  204. {
  205. return self::_request('api/'.static::_model()."/{$id}", 'DELETE');
  206. }
  207. /**
  208. * Lista todos os registros.
  209. *
  210. * @param int $inicio
  211. * @param int $limite
  212. *
  213. * @return string JSON
  214. */
  215. public static function listar(
  216. $inicio = 0,
  217. $limite = 10,
  218. $ordenarColuna = null,
  219. $ordenarDirecao = null,
  220. $filtros = null
  221. ) {
  222. $params = array(
  223. 'inicio='.$inicio,
  224. 'limite='.$limite,
  225. );
  226. if ($ordenarColuna !== null) {
  227. $params[] = 'ordenarColuna='.$ordenarColuna;
  228. }
  229. if ($ordenarDirecao !== null) {
  230. $params[] = 'ordenarDirecao='.$ordenarDirecao;
  231. }
  232. if ($filtros !== null) {
  233. if (is_array($filtros)) {
  234. $filtros = json_encode($filtros);
  235. }
  236. $params[] = 'filtros='.urlencode($filtros);
  237. }
  238. return self::_request('api/'.static::_model().'?'.implode('&', $params), 'GET');
  239. }
  240. }