Completed
Pull Request — master (#23)
by Roberto
07:08
created

Response::readRespStd()   C

Complexity

Conditions 8
Paths 3

Size

Total Lines 35
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 16

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 35
ccs 14
cts 28
cp 0.5
rs 5.3846
cc 8
eloc 24
nc 3
nop 1
crap 16
1
<?php
2
3
namespace NFePHP\Esfinge;
4
5
use DOMDocument;
6
7
class Response
8
{
9 15
    public static function readReturn($tag = '', $xmlResp = '')
10
    {
11 15
        if (trim($xmlResp) == '') {
12
            return [
13
                'bStat' => false,
14
                'message' => 'Não retornou nenhum dado'
15
            ];
16
        }
17 15
        libxml_use_internal_errors(true);
18 15
        $dom = new DOMDocument('1.0', 'utf-8');
19 15
        $dom->loadXML($xmlResp);
20 15
        $errors = libxml_get_errors();
21 15
        libxml_clear_errors();
22 15
        if (! empty($errors)) {
23
            return [
24
                'bStat' => false,
25
                'message' => $xmlResp,
26
                'errors' => $errors
27
            ];
28
        }
29
        //foi retornado um xml continue
30 15
        $reason = self::checkForFault($dom);
31 15
        if ($reason != '') {
32
            return [
33
                'bStat' => false,
34
                'message' => $reason
35
            ];
36
        }
37
        //converte o xml em uma StdClass
38 15
        $std = self::xml2Obj($dom, $tag);
39 15
        return self::readRespStd($std);
40
    }
41
    
42
    /**
43
     * Retorna os dados do objeto
44
     * @param StdClass $std
45
     * @return array
46
     */
47 15
    protected static function readRespStd($std)
48
    {
49 15
        if ($std->return->status == 'ERRO') {
50
            return [
51
                'bStat' => false,
52
                'message' => $std->return->mensagem,
53
                'status' => $std->return->status
54
            ];
55
        }
56
        $aResp = [
57 15
            'bStat' => true,
58 15
            'message' => $std->return->mensagem,
59 15
            'status' => $std->return->status
60 10
        ];
61 15
        $dados = $std->return->dados;
62 15
        if (property_exists($dados, 'entry')) {
63 6
            foreach ($std->return->dados->entry as $entry) {
64 6
                if (is_object($entry->value)) {
65
                    if (property_exists($entry->value, 'registros')) {
66
                        foreach ($entry->value->registros as $registro) {
67
                            $aReg[$registro->campo] = $registro->valor;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aReg was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aReg = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
68
                        }
69
                    } else {
70
                        foreach ($entry->value as $chave => $valor) {
71
                            $aReg[$chave] = $valor;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aReg was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aReg = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
72
                        }
73
                    }
74
                    $aResp[$entry->key] = $aReg;
0 ignored issues
show
Bug introduced by
The variable $aReg does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
75
                } else {
76 6
                    $aResp[$entry->key] = $entry->value;
77
                }
78 4
            }
79 4
        }
80 15
        return $aResp;
81
    }
82
    
83
    /**
84
     * Converte DOMDocument em uma StdClass com a tag desejada
85
     * @param DOMDocument $dom
86
     * @param string $tag
87
     * @return StdClass
88
     */
89 15
    protected static function xml2Obj($dom, $tag)
90
    {
91 15
        $node = $dom->getElementsByTagName($tag.'Response')->item(0);
92 15
        $newdoc = new DOMDocument('1.0', 'utf-8');
93 15
        $newdoc->appendChild($newdoc->importNode($node, true));
94 15
        $xml = $newdoc->saveXML();
95 15
        $newdoc = null;
0 ignored issues
show
Unused Code introduced by
$newdoc is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
96 15
        $xml = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $xml);
97 15
        $xml = str_replace('<?xml version="1.0" encoding="utf-8"?>', '', $xml);
98 15
        $resp = simplexml_load_string($xml, null, LIBXML_NOCDATA);
99 15
        $std = json_encode($resp);
100 15
        $std = str_replace('@attributes', 'attributes', $std);
101 15
        $std = json_decode($std);
102 15
        return $std;
103
    }
104
105
    /**
106
     * Verifica se o retorno é relativo a um ERRO SOAP
107
     *
108
     * @param DOMDocument $dom
109
     * @return string
110
     */
111 15
    public static function checkForFault($dom)
112
    {
113 15
        $tagfault = $dom->getElementsByTagName('Fault')->item(0);
114 15
        if (empty($tagfault)) {
115 15
            return '';
116
        }
117
        $tagreason = $tagfault->getElementsByTagName('Reason')->item(0);
118
        if (! empty($tagreason)) {
119
            $reason = $tagreason->getElementsByTagName('Text')->item(0)->nodeValue;
120
            return $reason;
121
        }
122
        return 'Houve uma falha na comunicação.';
123
    }
124
}
125