Completed
Push — master ( d546b5...54b7a9 )
by Eduardo
03:04
created

SoapNative::send()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 33
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 23
nc 2
nop 5
dl 0
loc 33
ccs 0
cts 20
cp 0
crap 42
rs 8.439
c 0
b 0
f 0
1
<?php
2
namespace Eduardokum\CorreiosPhp\Soap;
3
4
use Eduardokum\CorreiosPhp\Contracts\Soap\Soap as SoapContract;
5
use Eduardokum\CorreiosPhp\Exception\InvalidArgumentException;
6
use Eduardokum\CorreiosPhp\Exception\SoapException;
7
8
class SoapNative extends Soap implements SoapContract
9
{
10
    public function send($url, array $action = [], $request = '', $namespaces = [], $auth = [])
11
    {
12
        if (!array_key_exists('native', $action)) {
13
            throw new InvalidArgumentException('action for native not defined.');
14
        }
15
16
        $this->request = $this->xmlToStd($this->envelop($request, $namespaces));
17
        $params = [
18
            'encoding'           => 'UTF-8',
19
            'verifypeer'         => false,
20
            'verifyhost'         => false,
21
            'soap_version'       => SOAP_1_1,
22
            'trace'              => 1,
23
            'exceptions'         => 0,
24
            "connection_timeout" => $this->soapTimeout,
25
        ];
26
27
        if (array_key_exists('user', $auth) && array_key_exists('user', $auth)) {
28
            $params['login'] = $auth['user'];
29
            $params['password'] = $auth['password'];
30
        }
31
32
        try {
33
            $soapClient = new \SoapClient("$url?WSDL", $params);
34
            $this->response = $response = $soapClient->{$action['native']}($this->request);
35
            $this->soapInfo = $soapClient->__getLastResponseHeaders();
36
        } catch (\SoapFault $e) {
37
            throw new SoapException($e->getMessage());
38
        } catch (\Exception $e) {
39
            throw new SoapException($e->getMessage());
40
        }
41
42
        return $response;
43
    }
44
45
    /**
46
     * @param $xml
47
     *
48
     * @return \stdClass
49
     */
50
    private function xmlToStd($xml)
51
    {
52
        $dom = new \DOMDocument('1.0', 'UTF-8');
53
        $dom->preserveWhiteSpace = false;
54
        $dom->formatOutput = false;
55
        $dom->loadXML($xml);
56
57
        $response = $dom->getElementsByTagName('Body')
58
            ->item(0) // Get Body
59
            ->childNodes->item(0); // Get Result Object;
60
        $response = $dom->saveXML($response);
61
        $response = preg_replace('/\<(\/?)\w+:(\w+\/?)\>/', '<$1$2>', $response);
62
        $response  = simplexml_load_string($response);
63
        $response = json_encode($response, JSON_PRETTY_PRINT);
64
        return json_decode($response);
65
    }
66
}
67