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

Dom::addChild()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6
Metric Value
dl 0
loc 16
ccs 14
cts 14
cp 1
rs 8.8571
cc 6
eloc 11
nc 4
nop 6
crap 6
1
<?php
2
3
namespace NFePHP\Common\Dom;
4
5
/**
6
 * Classe auxiliar com funções de DOM extendidas
7
 * @category   NFePHP
8
 * @package    NFePHP\Common\DomDocument
9
 * @copyright  Copyright (c) 2008-2015
10
 * @license    http://www.gnu.org/licenses/lesser.html LGPL v3
11
 * @author     Roberto L. Machado <linux.rlm at gmail dot com>
12
 * @link       http://github.com/nfephp-org/nfephp for the canonical source repository
13
 */
14
15
use \DOMDocument;
16
use NFePHP\Common\Files\FilesFolders;
17
use NFePHP\Common\Exception;
18
19
class Dom extends DOMDocument
20
{
21
    /**
22
     * __construct
23
     * @param string $version
24
     * @param string $charset
25
     */
26 9
    public function __construct($version = '1.0', $charset = 'utf-8')
27
    {
28 9
        parent::__construct($version, $charset);
29 9
        $this->formatOutput = false;
30 9
        $this->preserveWhiteSpace = false;
31 9
    }
32
33 36
    public function loadXMLString($xmlString = '')
34
    {
35 36
        $msg = "O arquivo indicado não é um XML!";
36 36
        if (substr($xmlString, 0, 1) != '<') {
37 6
            throw new Exception\InvalidArgumentException($msg);
38
        }
39 30
        if (! $this->loadXML($xmlString, LIBXML_NOBLANKS | LIBXML_NOEMPTYTAG)) {
40
            throw new Exception\InvalidArgumentException($msg);
41
        }
42 30
    }
43
    
44 15
    public function loadXMLFile($pathXmlFile = '')
45
    {
46 15
        $data = FilesFolders::readFile($pathXmlFile);
47 15
        $this->loadXMLString($data);
48 12
    }
49
            
50
    /**
51
     * getNodeValue
52
     * Extrai o valor do node DOM
53
     * @param string $nodeName identificador da TAG do xml
54
     * @param int $itemNum numero do item a ser retornado
55
     * @param string $extraTextBefore prefixo do retorno
56
     * @param string $extraTextAfter sufixo do retorno
57
     * @return string
58
     */
59 9
    public function getNodeValue($nodeName, $itemNum = 0, $extraTextBefore = '', $extraTextAfter = '')
60
    {
61 9
        $node = $this->getElementsByTagName($nodeName)->item($itemNum);
62 9
        if (isset($node)) {
63 9
            $texto = html_entity_decode(trim($node->nodeValue), ENT_QUOTES, 'UTF-8');
64 9
            return $extraTextBefore . $texto . $extraTextAfter;
65
        }
66
        return '';
67
    }
68
    
69
    /**
70
     * getValue
71
     * @param DOMElement $node
72
     * @param string $name
73
     * @return string
74
     */
75
    public function getValue($node, $name)
76
    {
77
        if (empty($node)) {
78
            return '';
79
        }
80
        $texto = ! empty($node->getElementsByTagName($name)->item(0)->nodeValue) ?
81
            $node->getElementsByTagName($name)->item(0)->nodeValue : '';
82
        return html_entity_decode($texto, ENT_QUOTES, 'UTF-8');
83
    }
84
    
85
    /**
86
     * getNode
87
     * Retorna o node solicitado
88
     * @param string $nodeName
89
     * @param integer $itemNum
90
     * @return DOMElement se existir ou string vazia se não
91
     */
92 15
    public function getNode($nodeName, $itemNum = 0)
93
    {
94 15
        $node = $this->getElementsByTagName($nodeName)->item($itemNum);
95 15
        if (isset($node)) {
96 15
            return $node;
97
        }
98
        return '';
99
    }
100
    
101
    /**
102
     * getChave
103
     * @param string $nodeName
104
     * @return string
105
     */
106 6
    public function getChave($nodeName = 'infNFe')
107
    {
108 6
        $node = $this->getElementsByTagName($nodeName)->item(0);
109 6
        if (! empty($node)) {
110 6
            $chaveId = $node->getAttribute("Id");
111 6
            $chave =  preg_replace('/[^0-9]/', '', $chaveId);
112 6
            return $chave;
113
        }
114
        return '';
115
    }
116
    
117
    /**
118
     * addChild
119
     * Adiciona um elemento ao node xml passado como referencia
120
     * Serão inclusos erros na array $erros[] sempre que a tag for obrigatória e
121
     * nenhum parâmetro for passado na variável $content e $force for false
122
     * @param \DOMElement $parent
123
     * @param string $name
124
     * @param string $content
125
     * @param boolean $obrigatorio
126
     * @param string $descricao
127
     * @param boolean $force força a criação do elemento mesmo sem dados e não considera como erro
128
     * @return void
129
     */
130 6
    public function addChild(&$parent, $name, $content = '', $obrigatorio = false, $descricao = "", $force = false)
131
    {
132 6
        if ($obrigatorio && $content === '' && !$force) {
133 3
            $this->erros[] = array(
0 ignored issues
show
Bug introduced by
The property erros does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
134 3
                "tag" => $name,
135 3
                "desc" => $descricao,
136
                "erro" => "Preenchimento Obrigatório!"
137 3
            );
138 3
        }
139 6
        if ($obrigatorio || $content !== '') {
140 6
            $content = trim($content);
141 6
            $content = htmlspecialchars($content, ENT_QUOTES);
142 6
            $temp = $this->createElement($name, $content);
143 6
            $parent->appendChild($temp);
144 6
        }
145 6
    }
146
    
147
    /**
148
     * appChild
149
     * Acrescenta DOMElement a pai DOMElement
150
     * Caso o pai esteja vazio retorna uma exception com a mensagem
151
     * O parametro "child" pode ser vazio
152
     * @param \DOMNode $parent
153
     * @param \DOMNode $child
154
     * @param string $msg
155
     * @return void
156
     * @throws Exception\InvalidArgumentException
157
     */
158 6
    public function appChild(&$parent, $child, $msg = '')
159
    {
160 6
        if (empty($parent)) {
161 3
            throw new Exception\InvalidArgumentException($msg);
162
        }
163 3
        if (!empty($child)) {
164 3
            $parent->appendChild($child);
165 3
        }
166 3
    }
167
    
168
    /**
169
     * appChildBefore
170
     * Acrescenta DOMElement a pai DOMElement
171
     * Caso o pai esteja vazio retorna uma exception com a mensagem
172
     * O parametro "child" pode ser vazio
173
     * @param \DOMNode $parent
174
     * @param \DOMNode $child
175
     * @param string $before
176
     * @param string $msg
177
     * @return void
178
     * @throws Exception\InvalidArgumentException
179
     */
180
    public function appChildBefore(&$parent, $child, $before, $msg = '')
181
    {
182
        if (empty($parent)) {
183
            throw new Exception\InvalidArgumentException($msg);
184
        }
185
        $bnode = $parent->getElementsByTagName($before)->item(0);
186
        if (!empty($child) && !empty($bnode)) {
187
            $parent->insertBefore($child, $bnode);
188
        }
189
    }
190
    
191
    /**
192
     * addArrayChild
193
     * Adiciona a um DOMNode parent, outros elementos passados em um array de DOMElements
194
     * @param DOMElement $parent
195
     * @param array $arr
196
     * @return int
197
     */
198
    public function addArrayChild(&$parent, $arr)
199
    {
200
        $num = 0;
201
        if (! empty($arr) && ! empty($parent)) {
202
            foreach ($arr as $node) {
203
                $this->appChild($parent, $node, '');
204
                $num++;
205
            }
206
        }
207
        return $num;
208
    }
209
}
210