Skip to content

Commit b3ecd0f

Browse files
v1.0.0
0 parents  commit b3ecd0f

6 files changed

Lines changed: 433 additions & 0 deletions

File tree

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/vendor
2+
/nbproject
3+
.DS_Store
4+
/testes
5+
composer.lock

composer.json

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"name": "crphp/webservice",
3+
"type": "library",
4+
"description": "Biblioteca genérica para consumir webservice.",
5+
"keywords": ["webservice"],
6+
"license": "MIT",
7+
"support": {
8+
"issues": "https://github.com/crphp/webservice/issues",
9+
"source": "https://github.com/crphp/webservice"
10+
},
11+
"authors": [
12+
{
13+
"name": "Fábio Jânio",
14+
"email": "contato@fabiojanio.com"
15+
}
16+
],
17+
"require": {
18+
"php": ">=5.5.12"
19+
},
20+
"autoload": {
21+
"psr-4": {
22+
"Crphp\\Webservice\\": "src/"
23+
}
24+
},
25+
"minimum-stability": "dev"
26+
}

license

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
Copyright (c) fabiojanio.com
3+
4+
Permission is hereby granted, free of charge, to any person obtaining a copy
5+
of this software and associated documentation files (the "Software"), to deal
6+
in the Software without restriction, including without limitation the rights
7+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8+
copies of the Software, and to permit persons to whom the Software is
9+
furnished to do so, subject to the following conditions:
10+
11+
The above copyright notice and this permission notice shall be included in
12+
all copies or substantial portions of the Software.
13+
14+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20+
THE SOFTWARE.
21+

readme.md

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# crphp/webservice
2+
Está é uma biblioteca básica para se consumir um webservice. Este pacote permite
3+
o consumo via classe SoapClient ou via classe genéria construida com CURL.
4+
5+
1. [Funcionalidades](#funcionalidades)
6+
1. [Requisitos (recomendados)](#requisitos)
7+
1. [Baixando o pacote crphp/webservice para o servidor](#webservice)
8+
1. [Exemplos de uso](#exemplos)
9+
1. [Licença (MIT)](#licenca)
10+
11+
## 1 - <a id="funcionalidades"></a>Funcionalidades
12+
- [x] Consumir webservice
13+
- [x] Request XML
14+
- [x] Response XML
15+
- [x] Obter lista de métodos/serviços
16+
- [x] Formatar XML
17+
18+
## 2 - Requisitos (módulos)
19+
Os módulos abaixo se fazem necessário para que está biblioteca possa ser utilizada:
20+
- Curl
21+
- Soap
22+
23+
## 3 - <a id="webservice"></a>Baixando o pacote crphp/webservice para o servidor
24+
25+
Para a etapa abaixo estou pressupondo que você tenha o composer instalado e saiba utilizá-lo:
26+
```
27+
composer require crphp/webservice
28+
```
29+
30+
Ou se preferir criar um projeto:
31+
```
32+
composer create-project --prefer-dist crphp/webservice nome_projeto
33+
```
34+
35+
Caso ainda não tenha o composer instalado, obtenha este em: https://getcomposer.org/download/
36+
37+
## 4 - <a id="exemplos"></a>Exemplos de uso
38+
39+
**Utilizando a classe ClienteGenerico**:
40+
```php
41+
use Crphp\Webservice\ClienteGenerico;
42+
43+
// arquivo xml com cabeçalho
44+
$request = '<?xml version="1.0" encoding="UTF-8"?>
45+
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.webserviceX.NET/"><SOAP-ENV:Body></SOAP-ENV:Body></SOAP-ENV:Envelope>
46+
';
47+
48+
$obj = new ClienteGenerico;
49+
$obj->setURL('http://endereco_do_webservice');
50+
$obj->setRequest($request);
51+
$obj->run();
52+
53+
if($obj->getResponse())
54+
{
55+
// Perfumaria
56+
echo '<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>';
57+
echo "<pre class='prettyprint' >" . $obj->formatarXML() . "</pre>";
58+
}
59+
```
60+
61+
**Utilizando a classe Soap **
62+
```php
63+
use Crphp\Webservice\Soap;
64+
65+
$args = [
66+
'tag1_exemplo' => 'valor1',
67+
'tag2_exemplo' => 'valor2'
68+
];
69+
70+
$obj = new Soap;
71+
$obj->setWsdl('http://endereco_do_wsdl');
72+
73+
// Se o retorno for null então significa que a consulta não foi realizada
74+
if(!$obj->consultar('ConvertTemp', $args))
75+
{
76+
// Perfumaria
77+
echo '<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>';
78+
echo "<pre class='prettyprint' >" . $obj->formatarXML($obj->getResponse()) . "</pre>";
79+
}
80+
```
81+
82+
Os exemplos acima são simples, porém, as classes supracitadas possuem recursos que permitem validar se a
83+
requisição foi realizada com sucesso, bem como realizar outras validações.
84+
85+
## 5 - <a id="licenca">Licença (MIT)
86+
Leia o arquivo de licença para maiores informações.

src/ClienteGenerico.php

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
<?php
2+
3+
/**
4+
* Classe genérica de interação com webservice
5+
*
6+
* @package Crphp
7+
* @subpackage webservice
8+
* @author Fábio J L Ferreira <contato@fabiojanio.com>
9+
* @license MIT (consulte o arquivo license disponibilizado com este pacote)
10+
* @copyright (c) 2016, Fábio J L Ferreira
11+
*/
12+
13+
namespace Crphp\Webservice;
14+
15+
class ClienteGenerico
16+
{
17+
/**
18+
* Apontamento para uma instância de Curl
19+
*
20+
* @access private
21+
* @var object
22+
*/
23+
private $curl;
24+
25+
/**
26+
* Armazena o xml retornado pela consulta
27+
*
28+
* @var string
29+
*/
30+
private $xml;
31+
32+
/**
33+
* Armazena as informações referentes a requisição
34+
*
35+
* @var array
36+
*/
37+
private $info;
38+
39+
/**
40+
* Atribui alguns valores considerados padrão
41+
*
42+
* @access public
43+
*/
44+
public function __construct()
45+
{
46+
$this->curl = curl_init();
47+
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
48+
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
49+
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, 2);
50+
}
51+
52+
/**
53+
* Atribui a URL alvo e o tempo máximo de espera
54+
*
55+
* @param string $url
56+
* @param int $timeout
57+
*/
58+
public function setURL($url, $timeout = 30)
59+
{
60+
curl_setopt($this->curl, CURLOPT_URL, $url);
61+
curl_setopt($this->curl, CURLOPT_TIMEOUT, $timeout);
62+
}
63+
64+
/**
65+
* Define o agente a ser utilizado
66+
*
67+
* @param string $agente
68+
*/
69+
public function setAgent($agente = "PHP ClienteGenerico")
70+
{
71+
curl_setopt($this->curl, CURLOPT_USERAGENT, $agente);
72+
}
73+
74+
/**
75+
* Adiciona o conteúdo e atribui um cabeçalho a requisição
76+
*
77+
* @param string $post
78+
* @param array $header
79+
*/
80+
public function setRequest($post = null, array $header = null)
81+
{
82+
if (!$header)
83+
{
84+
$header = array(
85+
"Content-type: text/xml;charset=UTF-8",
86+
"Accept: text/xml",
87+
"Cache-Control: no-cache",
88+
"Pragma: no-cache",
89+
"Content-length: " . strlen($post),
90+
);
91+
}
92+
93+
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
94+
curl_setopt($this->curl, CURLOPT_POST, true);
95+
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $post);
96+
}
97+
98+
/**
99+
* Define regras de redirecionamento de URL
100+
*
101+
* @param bool $redirect
102+
* @param int $numRedirect
103+
* @param bool $refresh
104+
*/
105+
public function setRedirect($redirect = true, $numRedirect = 5, $refresh = true)
106+
{
107+
curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, $redirect);
108+
curl_setopt($this->curl, CURLOPT_MAXREDIRS, $numRedirect);
109+
curl_setopt($this->curl, CURLOPT_AUTOREFERER, $refresh);
110+
}
111+
112+
/**
113+
* Executa a consulta a URL alvo
114+
*
115+
* @return void|string em caso de sucesso retorna vazio, para erro retorna string
116+
*/
117+
public function run()
118+
{
119+
$this->xml = curl_exec($this->curl);
120+
$this->info = curl_getinfo($this->curl);
121+
curl_close($this->curl);
122+
}
123+
124+
/**
125+
* Informações da requisição obtidos do método curl_getinfo
126+
*
127+
* @see http://php.net/manual/pt_BR/function.curl-getinfo.php
128+
*
129+
* @return array
130+
*/
131+
public function getInfo()
132+
{
133+
return $this->info;
134+
}
135+
136+
/**
137+
* Retorna o output devolvido pelo servidor alvo
138+
*
139+
* @return void|string em caso de sucesso retorna vazio, para erro retorna string
140+
*/
141+
public function getResponse()
142+
{
143+
if($this->getInfo()['http_code'] === 500 || $this->getInfo()['http_code'] === 404)
144+
{
145+
return null;
146+
}
147+
148+
return $this->xml;
149+
}
150+
151+
/**
152+
* Formata o retorno do método getResponse
153+
*
154+
* @return null|string se não tiver dado para transformação retorna null
155+
*/
156+
public function formatarXML()
157+
{
158+
if(!$this->getResponse()) { return null; }
159+
160+
$dom = new \DOMDocument;
161+
$dom->preserveWhiteSpace = false;
162+
$dom->formatOutput = true;
163+
$dom->loadXML($this->getResponse());
164+
165+
return htmlentities($dom->saveXML());
166+
}
167+
}

0 commit comments

Comments
 (0)