Completed
Push — master ( 0803f0...703d5c )
by Esteban De La Fuente
01:58
created

Dte::getMontoTotal()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
dl 9
loc 9
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 0
1
<?php
2
3
/**
4
 * LibreDTE
5
 * Copyright (C) SASCO SpA (https://sasco.cl)
6
 *
7
 * Este programa es software libre: usted puede redistribuirlo y/o
8
 * modificarlo bajo los términos de la Licencia Pública General Affero de GNU
9
 * publicada por la Fundación para el Software Libre, ya sea la versión
10
 * 3 de la Licencia, o (a su elección) cualquier versión posterior de la
11
 * misma.
12
 *
13
 * Este programa se distribuye con la esperanza de que sea útil, pero
14
 * SIN GARANTÍA ALGUNA; ni siquiera la garantía implícita
15
 * MERCANTIL o de APTITUD PARA UN PROPÓSITO DETERMINADO.
16
 * Consulte los detalles de la Licencia Pública General Affero de GNU para
17
 * obtener una información más detallada.
18
 *
19
 * Debería haber recibido una copia de la Licencia Pública General Affero de GNU
20
 * junto a este programa.
21
 * En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
22
 */
23
24
namespace sasco\LibreDTE\Sii;
25
26
/**
27
 * Clase que representa un DTE y permite trabajar con el
28
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
29
 * @version 2016-07-15
30
 */
31
class Dte
32
{
33
34
    private $tipo; ///< Identificador del tipo de DTE: 33 (factura electrónica)
35
    private $folio; ///< Folio del documento
36
    private $xml; ///< Objeto XML que representa el DTE
37
    private $id; ///< Identificador único del DTE
38
    private $tipo_general; ///< Tipo general de DTE: Documento, Liquidacion o Exportaciones
39
    private $timestamp; ///< Timestamp del DTE
40
    private $datos = null; ///< Datos normalizados que se usaron para crear el DTE
41
    private $Signature = null; ///< Datos de la firma del DTE
42
43
    private $tipos = [
44
        'Documento' => [33, 34, 39, 41, 46, 52, 56, 61],
45
        'Liquidacion' => [43],
46
        'Exportaciones' => [110, 111, 112],
47
    ]; ///< Tipos posibles de documentos tributarios electrónicos
48
49
    private $noCedibles = [39, 41, 56, 61, 110, 111, 112]; ///< Documentos que no son cedibles
50
51
    /**
52
     * Constructor de la clase DTE
53
     * @param datos Arreglo con los datos del DTE o el XML completo del DTE
54
     * @param normalizar Si se pasa un arreglo permitirá indicar si el mismo se debe o no normalizar
55
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
56
     * @version 2015-09-03
57
     */
58
    public function __construct($datos, $normalizar = true)
59
    {
60
        if (is_array($datos))
61
            $this->setDatos($datos, $normalizar);
62
        else if (is_string($datos))
63
            $this->loadXML($datos);
64
        $this->timestamp = date('Y-m-d\TH:i:s');
65
    }
66
67
    /**
68
     * Método que carga el DTE ya armado desde un archivo XML
69
     * @param xml String con los datos completos del XML del DTE
70
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
71
     * @version 2016-09-01
72
     */
73
    private function loadXML($xml)
74
    {
75
        if (!empty($xml)) {
76
            $this->xml = new \sasco\LibreDTE\XML();
77
            if (!$this->xml->loadXML($xml) or !$this->schemaValidate()) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
78
                \sasco\LibreDTE\Log::write(
79
                    \sasco\LibreDTE\Estado::DTE_ERROR_LOADXML,
80
                    \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_LOADXML)
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...ado::DTE_ERROR_LOADXML) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
81
                );
82
                return false;
83
            }
84
            $TipoDTE = $this->xml->getElementsByTagName('TipoDTE')->item(0);
85
            if (!$TipoDTE) {
86
                return false;
87
            }
88
            $this->tipo = $TipoDTE->nodeValue;
89
            $this->tipo_general = $this->getTipoGeneral($this->tipo);
0 ignored issues
show
Documentation introduced by
$this->tipo is of type string, but the function expects a object<sasco\LibreDTE\Sii\Tipo>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
90
            if (!$this->tipo_general) {
91
                return false;
92
            }
93
            $Folio = $this->xml->getElementsByTagName('Folio')->item(0);
94
            if (!$Folio) {
95
                return false;
96
            }
97
            $this->folio = $Folio->nodeValue;
98
            if (isset($this->getDatos()['@attributes'])) {
99
                $this->id = $this->getDatos()['@attributes']['ID'];
100
            } else {
101
                $this->id = 'LibreDTE_T'.$this->tipo.'F'.$this->folio;
102
            }
103
            return true;
104
        }
105
        return false;
106
    }
107
108
    /**
109
     * Método que asigna los datos del DTE
110
     * @param datos Arreglo con los datos del DTE que se quire generar
111
     * @param normalizar Si se pasa un arreglo permitirá indicar si el mismo se debe o no normalizar
112
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
113
     * @version 2017-02-06
114
     */
115
    private function setDatos(array $datos, $normalizar = true)
116
    {
117
        if (!empty($datos)) {
118
            $this->tipo = $datos['Encabezado']['IdDoc']['TipoDTE'];
119
            $this->folio = $datos['Encabezado']['IdDoc']['Folio'];
120
            $this->id = 'LibreDTE_T'.$this->tipo.'F'.$this->folio;
121
            if ($normalizar) {
122
                $this->normalizar($datos);
123
                $method = 'normalizar_'.$this->tipo;
124
                if (method_exists($this, $method))
125
                    $this->$method($datos);
126
                $this->normalizar_final($datos);
127
            }
128
            $this->tipo_general = $this->getTipoGeneral($this->tipo);
129
            $this->xml = (new \sasco\LibreDTE\XML())->generate([
130
                'DTE' => [
131
                    '@attributes' => [
132
                        'version' => '1.0',
133
                    ],
134
                    $this->tipo_general => [
135
                        '@attributes' => [
136
                            'ID' => $this->id
137
                        ],
138
                    ]
139
                ]
140
            ]);
141
            $parent = $this->xml->getElementsByTagName($this->tipo_general)->item(0);
142
            $this->xml->generate($datos + ['TED' => null], $parent);
0 ignored issues
show
Documentation introduced by
$parent is of type object<DOMNode>, but the function expects a null|object<DOMElement>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
143
            $this->datos = $datos;
144
            if (!$this->verificarDatos())
145
                return false;
146
            return $this->schemaValidate();
147
        }
148
        return false;
149
    }
150
151
    /**
152
     * Método que entrega el arreglo con los datos del DTE.
153
     * Si el DTE fue creado a partir de un arreglo serán los datos normalizados,
154
     * en cambio si se creó a partir de un XML serán todos los nodos del
155
     * documento sin cambios.
156
     * @return Arreglo con datos del DTE
157
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
158
     * @version 2016-07-04
159
     */
160
    public function getDatos()
161
    {
162
        if (!$this->datos) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->datos of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
163
            $datos = $this->xml->toArray();
164
            if (!isset($datos['DTE'][$this->tipo_general])) {
165
                \sasco\LibreDTE\Log::write(
166
                    \sasco\LibreDTE\Estado::DTE_ERROR_GETDATOS,
167
                    \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_GETDATOS)
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...do::DTE_ERROR_GETDATOS) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
168
                );
169
                return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getDatos of type sasco\LibreDTE\Sii\Arreglo.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
170
            }
171
            $this->datos = $datos['DTE'][$this->tipo_general];
172
            if (isset($datos['DTE']['Signature'])) {
173
                $this->Signature = $datos['DTE']['Signature'];
174
            }
175
        }
176
        return $this->datos;
177
    }
178
179
    /**
180
     * Método que entrega el arreglo con los datos de la firma del DTE
181
     * @return Arreglo con datos de la firma
182
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
183
     * @version 2016-06-11
184
     */
185
    public function getFirma()
186
    {
187
        if (!$this->Signature) {
188
            $this->getDatos();
189
        }
190
        return $this->Signature;
191
    }
192
193
    /**
194
     * Método que entrega los datos del DTE (tag Documento) como un string JSON
195
     * @return String JSON "lindo" con los datos del documento
196
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
197
     * @version 2015-09-08
198
     */
199
    public function getJSON()
200
    {
201
        if (!$this->getDatos())
202
            return false;
203
        return json_encode($this->datos, JSON_PRETTY_PRINT);
204
    }
205
206
    /**
207
     * Método que entrega el ID del documento
208
     * @return String con el ID del DTE
209
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
210
     * @version 2016-08-17
211
     */
212
    public function getID($estandar = false)
213
    {
214
        return $estandar ? ('T'.$this->tipo.'F'.$this->folio) : $this->id;
215
    }
216
217
    /**
218
     * Método que entrega el tipo general de documento, de acuerdo a
219
     * $this->tipos
220
     * @param dte Tipo númerico de DTE, ejemplo: 33 (factura electrónica)
221
     * @return String con el tipo general: Documento, Liquidacion o Exportaciones
222
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
223
     * @version 2015-09-17
224
     */
225
    private function getTipoGeneral($dte)
226
    {
227
        foreach ($this->tipos as $tipo => $codigos)
228
            if (in_array($dte, $codigos))
229
                return $tipo;
230
        \sasco\LibreDTE\Log::write(
231
            \sasco\LibreDTE\Estado::DTE_ERROR_TIPO,
232
            \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_TIPO, $dte)
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...::DTE_ERROR_TIPO, $dte) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
233
        );
234
        return false;
235
    }
236
237
    /**
238
     * Método que entrega el tipo de DTE
239
     * @return Tipo de dte, ej: 33 (factura electrónica)
240
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
241
     * @version 2015-09-02
242
     */
243
    public function getTipo()
244
    {
245
        return $this->tipo;
246
    }
247
248
    /**
249
     * Método que entrega el folio del DTE
250
     * @return Folio del DTE
251
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
252
     * @version 2015-09-02
253
     */
254
    public function getFolio()
255
    {
256
        return $this->folio;
257
    }
258
259
    /**
260
     * Método que entrega rut del emisor del DTE
261
     * @return RUT del emiro
262
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
263
     * @version 2015-09-07
264
     */
265 View Code Duplication
    public function getEmisor()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
266
    {
267
        $nodo = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Emisor/RUTEmisor')->item(0);
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...ezado/Emisor/RUTEmisor' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
268
        if ($nodo)
269
            return $nodo->nodeValue;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $nodo->nodeValue; (string) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getEmisor of type sasco\LibreDTE\Sii\RUT.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
270
        if (!$this->getDatos())
271
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getEmisor of type sasco\LibreDTE\Sii\RUT.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
272
        return $this->datos['Encabezado']['Emisor']['RUTEmisor'];
273
    }
274
275
    /**
276
     * Método que entrega rut del receptor del DTE
277
     * @return RUT del emiro
278
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
279
     * @version 2015-09-07
280
     */
281 View Code Duplication
    public function getReceptor()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
282
    {
283
        $nodo = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Receptor/RUTRecep')->item(0);
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...zado/Receptor/RUTRecep' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
284
        if ($nodo)
285
            return $nodo->nodeValue;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $nodo->nodeValue; (string) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getReceptor of type sasco\LibreDTE\Sii\RUT.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
286
        if (!$this->getDatos())
287
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getReceptor of type sasco\LibreDTE\Sii\RUT.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
288
        return $this->datos['Encabezado']['Receptor']['RUTRecep'];
289
    }
290
291
    /**
292
     * Método que entrega fecha de emisión del DTE
293
     * @return Fecha de emisión en formato AAAA-MM-DD
294
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
295
     * @version 2015-09-07
296
     */
297 View Code Duplication
    public function getFechaEmision()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
298
    {
299
        $nodo = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/FchEmis')->item(0);
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...cabezado/IdDoc/FchEmis' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
300
        if ($nodo)
301
            return $nodo->nodeValue;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $nodo->nodeValue; (string) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getFechaEmision of type sasco\LibreDTE\Sii\Fecha.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
302
        if (!$this->getDatos())
303
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getFechaEmision of type sasco\LibreDTE\Sii\Fecha.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
304
        return $this->datos['Encabezado']['IdDoc']['FchEmis'];
305
    }
306
307
    /**
308
     * Método que entrega el monto total del DTE
309
     * @return Monto total del DTE
310
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
311
     * @version 2015-09-07
312
     */
313 View Code Duplication
    public function getMontoTotal()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
314
    {
315
        $nodo = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Totales/MntTotal')->item(0);
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...ezado/Totales/MntTotal' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
316
        if ($nodo)
317
            return $nodo->nodeValue;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $nodo->nodeValue; (string) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getMontoTotal of type sasco\LibreDTE\Sii\Monto.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
318
        if (!$this->getDatos())
319
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getMontoTotal of type sasco\LibreDTE\Sii\Monto.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
320
        return $this->datos['Encabezado']['Totales']['MntTotal'];
321
    }
322
323
    /**
324
     * Método que entrega el tipo de moneda del documento
325
     * @return String con el tipo de moneda
326
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
327
     * @version 2016-07-16
328
     */
329 View Code Duplication
    public function getMoneda()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
330
    {
331
        $nodo = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Totales/TpoMoneda')->item(0);
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...zado/Totales/TpoMoneda' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
332
        if ($nodo)
333
            return $nodo->nodeValue;
334
        if (!$this->getDatos())
335
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getMoneda of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
336
        return $this->datos['Encabezado']['Totales']['TpoMoneda'];
337
    }
338
339
    /**
340
     * Método que entrega el string XML del tag TED
341
     * @return String XML con tag TED
342
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
343
     * @version 2016-08-03
344
     */
345
    public function getTED()
346
    {
347
        /*$xml = new \sasco\LibreDTE\XML();
0 ignored issues
show
Unused Code Comprehensibility introduced by
68% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
348
        $xml->loadXML($this->xml->getElementsByTagName('TED')->item(0)->getElementsByTagName('DD')->item(0)->C14N());
349
        $xml->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
350
        $xml->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
351
        $FRMT = $this->xml->getElementsByTagName('TED')->item(0)->getElementsByTagName('FRMT')->item(0)->nodeValue;
352
        $pub_key = '';
353
        if (openssl_verify($xml->getFlattened('/'), base64_decode($FRMT), $pub_key, OPENSSL_ALGO_SHA1)!==1);
354
            return false;*/
355
        $xml = new \sasco\LibreDTE\XML();
356
        $TED = $this->xml->getElementsByTagName('TED')->item(0);
357
        if (!$TED)
358
            return '<TED/>';
359
        $xml->loadXML($TED->C14N());
360
        $xml->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
361
        $xml->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
362
        $TED = $xml->getFlattened('/');
0 ignored issues
show
Documentation introduced by
'/' is of type string, but the function expects a object<sasco\LibreDTE\XPath>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
363
        return mb_detect_encoding($TED, ['UTF-8', 'ISO-8859-1']) != 'ISO-8859-1' ? utf8_decode($TED) : $TED;
364
    }
365
366
    /**
367
     * Método que indica si el DTE es de certificación o no
368
     * @return =true si el DTE es de certificación, =null si no se pudo determinar
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
369
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
370
     * @version 2016-06-15
371
     */
372
    public function getCertificacion()
373
    {
374
        $datos = $this->getDatos();
375
        $idk = !empty($datos['TED']['DD']['CAF']['DA']['IDK']) ? (int)$datos['TED']['DD']['CAF']['DA']['IDK'] : null;
376
        return $idk ? $idk === 100 : null;
377
    }
378
379
    /**
380
     * Método que realiza el timbrado del DTE
381
     * @param Folios Objeto de los Folios con los que se desea timbrar
382
     * @return =true si se pudo timbrar o =false en caso de error
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
383
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
384
     * @version 2016-09-01
385
     */
386
    public function timbrar(Folios $Folios)
387
    {
388
        // verificar que el folio que se está usando para el DTE esté dentro
389
        // del rango de folios autorizados que se usarán para timbrar
390
        // Esta validación NO verifica si el folio ya fue usado, sólo si está
391
        // dentro del CAF que se está usando
392
        $folio = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/Folio')->item(0)->nodeValue;
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...Encabezado/IdDoc/Folio' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
393
        if ($folio<$Folios->getDesde() or $folio>$Folios->getHasta()) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
394
            \sasco\LibreDTE\Log::write(
395
                \sasco\LibreDTE\Estado::DTE_ERROR_RANGO_FOLIO,
396
                \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_RANGO_FOLIO, $this->getID())
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::..._FOLIO, $this->getID()) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
397
            );
398
            return false;
399
        }
400
        // verificar que existan datos para el timbre
401 View Code Duplication
        if (!$this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/FchEmis')->item(0)) {
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...cabezado/IdDoc/FchEmis' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
402
            \sasco\LibreDTE\Log::write(
403
                \sasco\LibreDTE\Estado::DTE_FALTA_FCHEMIS,
404
                \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_FALTA_FCHEMIS, $this->getID())
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...CHEMIS, $this->getID()) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
405
            );
406
            \sasco\LibreDTE\Log::write('Falta FchEmis del DTE '.$this->getID());
0 ignored issues
show
Documentation introduced by
'Falta FchEmis del DTE ' . $this->getID() is of type string, but the function expects a object<sasco\LibreDTE\Código>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
407
            return false;
408
        }
409 View Code Duplication
        if (!$this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Totales/MntTotal')->item(0)) {
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...ezado/Totales/MntTotal' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
410
            \sasco\LibreDTE\Log::write(
411
                \sasco\LibreDTE\Estado::DTE_FALTA_MNTTOTAL,
412
                \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_FALTA_MNTTOTAL, $this->getID())
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...TTOTAL, $this->getID()) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
413
            );
414
            return false;
415
        }
416
        // timbrar
417
        $RR = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Receptor/RUTRecep')->item(0)->nodeValue;
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...zado/Receptor/RUTRecep' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
418
        $RSR_nodo = $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Receptor/RznSocRecep');
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...o/Receptor/RznSocRecep' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
419
        $RSR = $RSR_nodo->length ? trim(mb_substr($RSR_nodo->item(0)->nodeValue, 0, 40)) : $RR;
420
        $TED = new \sasco\LibreDTE\XML();
421
        $TED->generate([
422
            'TED' => [
423
                '@attributes' => [
424
                    'version' => '1.0',
425
                ],
426
                'DD' => [
427
                    'RE' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Emisor/RUTEmisor')->item(0)->nodeValue,
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...ezado/Emisor/RUTEmisor' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
428
                    'TD' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/TipoDTE')->item(0)->nodeValue,
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...cabezado/IdDoc/TipoDTE' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
429
                    'F' => $folio,
430
                    'FE' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/IdDoc/FchEmis')->item(0)->nodeValue,
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...cabezado/IdDoc/FchEmis' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
431
                    'RR' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Receptor/RUTRecep')->item(0)->nodeValue,
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...zado/Receptor/RUTRecep' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
432
                    'RSR' => $RSR,
433
                    'MNT' => $this->xml->xpath('/DTE/'.$this->tipo_general.'/Encabezado/Totales/MntTotal')->item(0)->nodeValue,
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_ge...ezado/Totales/MntTotal' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
434
                    'IT1' => trim(mb_substr($this->xml->xpath('/DTE/'.$this->tipo_general.'/Detalle')->item(0)->getElementsByTagName('NmbItem')->item(0)->nodeValue, 0, 40)),
0 ignored issues
show
Documentation introduced by
'/DTE/' . $this->tipo_general . '/Detalle' is of type string, but the function expects a object<sasco\LibreDTE\Expresión>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
435
                    'CAF' => $Folios->getCaf(),
436
                    'TSTED' => $this->timestamp,
437
                ],
438
                'FRMT' => [
439
                    '@attributes' => [
440
                        'algoritmo' => 'SHA1withRSA'
441
                    ],
442
                ],
443
            ]
444
        ]);
445
        $DD = $TED->getFlattened('/TED/DD');
0 ignored issues
show
Documentation introduced by
'/TED/DD' is of type string, but the function expects a object<sasco\LibreDTE\XPath>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
446
        if (openssl_sign($DD, $timbre, $Folios->getPrivateKey(), OPENSSL_ALGO_SHA1)==false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
447
            \sasco\LibreDTE\Log::write(
448
                \sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE,
449
                \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE, $this->getID())
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...TIMBRE, $this->getID()) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
450
            );
451
            return false;
452
        }
453
        $TED->getElementsByTagName('FRMT')->item(0)->nodeValue = base64_encode($timbre);
454
        $xml = str_replace('<TED/>', trim(str_replace('<?xml version="1.0" encoding="ISO-8859-1"?>', '', $TED->saveXML())), $this->saveXML());
455 View Code Duplication
        if (!$this->loadXML($xml)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
456
            \sasco\LibreDTE\Log::write(
457
                \sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE,
458
                \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE, $this->getID())
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...TIMBRE, $this->getID()) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
459
            );
460
            return false;
461
        }
462
        return true;
463
    }
464
465
    /**
466
     * Método que realiza la firma del DTE
467
     * @param Firma objeto que representa la Firma Electrónca
468
     * @return =true si el DTE pudo ser fimado o =false si no se pudo firmar
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
469
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
470
     * @version 2015-09-17
471
     */
472
    public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
473
    {
474
        $parent = $this->xml->getElementsByTagName($this->tipo_general)->item(0);
475
        $this->xml->generate(['TmstFirma'=>$this->timestamp], $parent);
0 ignored issues
show
Documentation introduced by
$parent is of type object<DOMNode>, but the function expects a null|object<DOMElement>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
476
        $xml = $Firma->signXML($this->xml->saveXML(), '#'.$this->id, $this->tipo_general);
0 ignored issues
show
Documentation introduced by
$this->xml->saveXML() is of type string, but the function expects a object<sasco\LibreDTE\Datos>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
477 View Code Duplication
        if (!$xml) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
478
            \sasco\LibreDTE\Log::write(
479
                \sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
480
                \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA, $this->getID())
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::..._FIRMA, $this->getID()) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
481
            );
482
            return false;
483
        }
484
        $this->loadXML($xml);
0 ignored issues
show
Bug introduced by
It seems like $xml defined by $Firma->signXML($this->x...d, $this->tipo_general) on line 476 can also be of type boolean; however, sasco\LibreDTE\Sii\Dte::loadXML() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
485
        return true;
486
    }
487
488
    /**
489
     * Método que entrega el DTE en XML
490
     * @return XML con el DTE (podría: con o sin timbre y con o sin firma)
491
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
492
     * @version 2015-08-20
493
     */
494
    public function saveXML()
495
    {
496
        return $this->xml->saveXML();
497
    }
498
499
    /**
500
     * Método que genera un arreglo con el resumen del documento. Este resumen
501
     * puede servir, por ejemplo, para generar los detalles de los IECV
502
     * @return Arreglo con el resumen del DTE
503
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
504
     * @version 2016-07-15
505
     */
506
    public function getResumen()
507
    {
508
        $this->getDatos();
509
        // generar resumen
510
        $resumen =  [
511
            'TpoDoc' => (int)$this->datos['Encabezado']['IdDoc']['TipoDTE'],
512
            'NroDoc' => (int)$this->datos['Encabezado']['IdDoc']['Folio'],
513
            'TasaImp' => 0,
514
            'FchDoc' => $this->datos['Encabezado']['IdDoc']['FchEmis'],
515
            'CdgSIISucur' => !empty($this->datos['Encabezado']['Emisor']['CdgSIISucur']) ? $this->datos['Encabezado']['Emisor']['CdgSIISucur'] : false,
516
            'RUTDoc' => $this->datos['Encabezado']['Receptor']['RUTRecep'],
517
            'RznSoc' => isset($this->datos['Encabezado']['Receptor']['RznSocRecep']) ? $this->datos['Encabezado']['Receptor']['RznSocRecep'] : false,
518
            'MntExe' => false,
519
            'MntNeto' => false,
520
            'MntIVA' => 0,
521
            'MntTotal' => 0,
522
        ];
523
        // obtener montos si es que existen en el documento
524
        $montos = ['TasaImp'=>'TasaIVA', 'MntExe'=>'MntExe', 'MntNeto'=>'MntNeto', 'MntIVA'=>'IVA', 'MntTotal'=>'MntTotal'];
525
        foreach ($montos as $dest => $orig) {
526
            if (!empty($this->datos['Encabezado']['Totales'][$orig])) {
527
                $resumen[$dest] = !$this->esExportacion() ? round($this->datos['Encabezado']['Totales'][$orig]) : $this->datos['Encabezado']['Totales'][$orig];
528
            }
529
        }
530
        // si es una boleta se calculan los datos para el resumen
531
        if ($this->esBoleta()) {
532
            if (!$resumen['TasaImp']) {
533
                $resumen['TasaImp'] = \sasco\LibreDTE\Sii::getIVA();
534
            }
535
            $resumen['MntExe'] = (int)$resumen['MntExe'];
536
            if (!$resumen['MntNeto']) {
537
                list($resumen['MntNeto'], $resumen['MntIVA']) = $this->calcularNetoIVA($resumen['MntTotal']-$resumen['MntExe'], $resumen['TasaImp']);
0 ignored issues
show
Documentation introduced by
$resumen['MntTotal'] - $resumen['MntExe'] is of type integer|double, but the function expects a object<sasco\LibreDTE\Sii\neto>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
538
            }
539
        }
540
        // entregar resumen
541
        return $resumen;
542
    }
543
544
    /**
545
     * Método que permite obtener el monto neto y el IVA de ese neto a partir de
546
     * un monto total
547
     * @param total neto + iva
548
     * @param tasa Tasa del IVA
549
     * @return Arreglo con el neto y el iva
550
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
551
     * @version 2016-04-05
552
     */
553
    private function calcularNetoIVA($total, $tasa = null)
554
    {
555
        if ($tasa === 0 or $tasa === false)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
556
            return [0, 0];
557
        if ($tasa === null)
558
            $tasa = \sasco\LibreDTE\Sii::getIVA();
559
        // WARNING: el IVA obtenido puede no ser el NETO*(TASA/100)
560
        // se calcula el monto neto y luego se obtiene el IVA haciendo la resta
561
        // entre el total y el neto, ya que hay casos de borde como:
562
        //  - BRUTO:   680 => NETO:   571 e IVA:   108 => TOTAL:   679
563
        //  - BRUTO: 86710 => NETO: 72866 e IVA: 13845 => TOTAL: 86711
564
        $neto = round($total / (1+($tasa/100)));
565
        $iva = $total - $neto;
566
        return [$neto, $iva];
567
    }
568
569
    /**
570
     * Método que normaliza los datos de un documento tributario electrónico
571
     * @param datos Arreglo con los datos del documento que se desean normalizar
572
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
573
     * @version 2017-07-24
574
     */
575
    private function normalizar(array &$datos)
576
    {
577
        // completar con nodos por defecto
578
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
579
            'Encabezado' => [
580
                'IdDoc' => [
581
                    'TipoDTE' => false,
582
                    'Folio' => false,
583
                    'FchEmis' => date('Y-m-d'),
584
                    'IndNoRebaja' => false,
585
                    'TipoDespacho' => false,
586
                    'IndTraslado' => false,
587
                    'TpoImpresion' => false,
588
                    'IndServicio' => $this->esBoleta() ? 3 : false,
589
                    'MntBruto' => false,
590
                    'FmaPago' => false,
591
                    'FmaPagExp' => false,
592
                    'MntCancel' => false,
593
                    'SaldoInsol' => false,
594
                    'FchCancel' => false,
595
                    'MntPagos' => false,
596
                    'PeriodoDesde' => false,
597
                    'PeriodoHasta' => false,
598
                    'MedioPago' => false,
599
                    'TpoCtaPago' => false,
600
                    'NumCtaPago' => false,
601
                    'BcoPago' => false,
602
                    'TermPagoCdg' => false,
603
                    'TermPagoGlosa' => false,
604
                    'TermPagoDias' => false,
605
                    'FchVenc' => false,
606
                ],
607
                'Emisor' => [
608
                    'RUTEmisor' => false,
609
                    'RznSoc' => false,
610
                    'GiroEmis' => false,
611
                    'Telefono' => false,
612
                    'CorreoEmisor' => false,
613
                    'Acteco' => false,
614
                    'Sucursal' => false,
615
                    'CdgSIISucur' => false,
616
                    'DirOrigen' => false,
617
                    'CmnaOrigen' => false,
618
                    'CiudadOrigen' => false,
619
                    'CdgVendedor' => false,
620
                ],
621
                'Receptor' => [
622
                    'RUTRecep' => false,
623
                    'CdgIntRecep' => false,
624
                    'RznSocRecep' => false,
625
                    'Extranjero' => false,
626
                    'GiroRecep' => false,
627
                    'Contacto' => false,
628
                    'CorreoRecep' => false,
629
                    'DirRecep' => false,
630
                    'CmnaRecep' => false,
631
                    'CiudadRecep' => false,
632
                    'DirPostal' => false,
633
                    'CmnaPostal' => false,
634
                    'CiudadPostal' => false,
635
                ],
636
                'Totales' => [
637
                    'TpoMoneda' => false,
638
                ],
639
            ],
640
            'Detalle' => false,
641
            'SubTotInfo' => false,
642
            'DscRcgGlobal' => false,
643
            'Referencia' => false,
644
            'Comisiones' => false,
645
        ], $datos);
646
        // corregir algunos datos que podrían venir malos para no caer por schema
647
        $datos['Encabezado']['Emisor']['RUTEmisor'] = strtoupper($datos['Encabezado']['Emisor']['RUTEmisor']);
648
        $datos['Encabezado']['Receptor']['RUTRecep'] = strtoupper($datos['Encabezado']['Receptor']['RUTRecep']);
649
        $datos['Encabezado']['Receptor']['RznSocRecep'] = mb_substr($datos['Encabezado']['Receptor']['RznSocRecep'], 0, 100);
650 View Code Duplication
        if (!empty($datos['Encabezado']['Receptor']['GiroRecep'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
651
            $datos['Encabezado']['Receptor']['GiroRecep'] = mb_substr($datos['Encabezado']['Receptor']['GiroRecep'], 0, 40);
652
        }
653 View Code Duplication
        if (!empty($datos['Encabezado']['Receptor']['Contacto'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
654
            $datos['Encabezado']['Receptor']['Contacto'] = mb_substr($datos['Encabezado']['Receptor']['Contacto'], 0, 80);
655
        }
656 View Code Duplication
        if (!empty($datos['Encabezado']['Receptor']['CorreoRecep'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
657
            $datos['Encabezado']['Receptor']['CorreoRecep'] = mb_substr($datos['Encabezado']['Receptor']['CorreoRecep'], 0, 80);
658
        }
659 View Code Duplication
        if (!empty($datos['Encabezado']['Receptor']['DirRecep'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
660
            $datos['Encabezado']['Receptor']['DirRecep'] = mb_substr($datos['Encabezado']['Receptor']['DirRecep'], 0, 70);
661
        }
662 View Code Duplication
        if (!empty($datos['Encabezado']['Receptor']['CmnaRecep'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
663
            $datos['Encabezado']['Receptor']['CmnaRecep'] = mb_substr($datos['Encabezado']['Receptor']['CmnaRecep'], 0, 20);
664
        }
665
        // si existe descuento o recargo global se normalizan
666
        if (!empty($datos['DscRcgGlobal'])) {
667 View Code Duplication
            if (!isset($datos['DscRcgGlobal'][0]))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
668
                $datos['DscRcgGlobal'] = [$datos['DscRcgGlobal']];
669
            $NroLinDR = 1;
670
            foreach ($datos['DscRcgGlobal'] as &$dr) {
671
                $dr = array_merge([
672
                    'NroLinDR' => $NroLinDR++,
673
                ], $dr);
674
            }
675
        }
676
        // si existe una o más referencias se normalizan
677
        if (!empty($datos['Referencia'])) {
678 View Code Duplication
            if (!isset($datos['Referencia'][0]))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
679
                $datos['Referencia'] = [$datos['Referencia']];
680
            $NroLinRef = 1;
681
            foreach ($datos['Referencia'] as &$r) {
682
                $r = array_merge([
683
                    'NroLinRef' => $NroLinRef++,
684
                    'TpoDocRef' => false,
685
                    'IndGlobal' => false,
686
                    'FolioRef' => false,
687
                    'RUTOtr' => false,
688
                    'FchRef' => date('Y-m-d'),
689
                    'CodRef' => false,
690
                    'RazonRef' => false,
691
                ], $r);
692
            }
693
        }
694
    }
695
696
    /**
697
     * Método que realiza la normalización final de los datos de un documento
698
     * tributario electrónico. Esto se aplica todos los documentos una vez que
699
     * ya se aplicaron las normalizaciones por tipo
700
     * @param datos Arreglo con los datos del documento que se desean normalizar
701
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
702
     * @version 2016-02-28
703
     */
704
    private function normalizar_final(array &$datos)
705
    {
706
        // normalizar montos de pagos programados
707
        if (is_array($datos['Encabezado']['IdDoc']['MntPagos'])) {
708
            $montos = 0;
0 ignored issues
show
Unused Code introduced by
$montos 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...
709
            if (!isset($datos['Encabezado']['IdDoc']['MntPagos'][0]))
710
                $datos['Encabezado']['IdDoc']['MntPagos'] = [$datos['Encabezado']['IdDoc']['MntPagos']];
711
            foreach ($datos['Encabezado']['IdDoc']['MntPagos'] as &$MntPagos) {
712
                $MntPagos = array_merge([
713
                    'FchPago' => null,
714
                    'MntPago' => null,
715
                    'GlosaPagos' => false,
716
                ], $MntPagos);
717
                if ($MntPagos['MntPago']===null) {
718
                    $MntPagos['MntPago'] = $datos['Encabezado']['Totales']['MntTotal'];
719
                }
720
            }
721
        }
722
    }
723
724
    /**
725
     * Método que normaliza los datos de una factura electrónica
726
     * @param datos Arreglo con los datos del documento que se desean normalizar
727
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
728
     * @version 2016-08-18
729
     */
730
    private function normalizar_33(array &$datos)
731
    {
732
        // completar con nodos por defecto
733
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
734
            'Encabezado' => [
735
                'IdDoc' => false,
736
                'Emisor' => false,
737
                'RUTMandante' => false,
738
                'Receptor' => false,
739
                'RUTSolicita' => false,
740
                'Transporte' => false,
741
                'Totales' => [
742
                    'MntNeto' => 0,
743
                    'MntExe' => false,
744
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
745
                    'IVA' => 0,
746
                    'ImptoReten' => false,
747
                    'CredEC' => false,
748
                    'MntTotal' => 0,
749
                ],
750
                'OtraMoneda' => false,
751
            ],
752
        ], $datos);
753
        // normalizar datos
754
        $this->normalizar_detalle($datos);
755
        $this->normalizar_aplicar_descuentos_recargos($datos);
756
        $this->normalizar_impuesto_retenido($datos);
757
        $this->normalizar_agregar_IVA_MntTotal($datos);
758
    }
759
760
    /**
761
     * Método que normaliza los datos de una factura exenta electrónica
762
     * @param datos Arreglo con los datos del documento que se desean normalizar
763
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
764
     * @version 2017-02-23
765
     */
766
    private function normalizar_34(array &$datos)
767
    {
768
        // completar con nodos por defecto
769
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
770
            'Encabezado' => [
771
                'IdDoc' => false,
772
                'Emisor' => false,
773
                'Receptor' => false,
774
                'RUTSolicita' => false,
775
                'Totales' => [
776
                    'MntExe' => false,
777
                    'MntTotal' => 0,
778
                ]
779
            ],
780
        ], $datos);
781
        // normalizar datos
782
        $this->normalizar_detalle($datos);
783
        $this->normalizar_aplicar_descuentos_recargos($datos);
784
        $this->normalizar_agregar_IVA_MntTotal($datos);
785
    }
786
787
    /**
788
     * Método que normaliza los datos de una boleta electrónica
789
     * @param datos Arreglo con los datos del documento que se desean normalizar
790
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
791
     * @version 2016-03-14
792
     */
793 View Code Duplication
    private function normalizar_39(array &$datos)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
794
    {
795
        // completar con nodos por defecto
796
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
797
            'Encabezado' => [
798
                'IdDoc' => false,
799
                'Emisor' => [
800
                    'RUTEmisor' => false,
801
                    'RznSocEmisor' => false,
802
                    'GiroEmisor' => false,
803
                ],
804
                'Receptor' => false,
805
                'Totales' => [
806
                    'MntExe' => false,
807
                    'MntTotal' => 0,
808
                ]
809
            ],
810
        ], $datos);
811
        // normalizar datos
812
        $this->normalizar_boletas($datos);
813
        $this->normalizar_detalle($datos);
814
        $this->normalizar_aplicar_descuentos_recargos($datos);
815
        $this->normalizar_agregar_IVA_MntTotal($datos);
816
    }
817
818
    /**
819
     * Método que normaliza los datos de una boleta exenta electrónica
820
     * @param datos Arreglo con los datos del documento que se desean normalizar
821
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
822
     * @version 2016-03-14
823
     */
824 View Code Duplication
    private function normalizar_41(array &$datos)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
825
    {
826
        // completar con nodos por defecto
827
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
828
            'Encabezado' => [
829
                'IdDoc' => false,
830
                'Emisor' => [
831
                    'RUTEmisor' => false,
832
                    'RznSocEmisor' => false,
833
                    'GiroEmisor' => false,
834
                ],
835
                'Receptor' => false,
836
                'Totales' => [
837
                    'MntExe' => 0,
838
                    'MntTotal' => 0,
839
                ]
840
            ],
841
        ], $datos);
842
        // normalizar datos
843
        $this->normalizar_boletas($datos);
844
        $this->normalizar_detalle($datos);
845
        $this->normalizar_aplicar_descuentos_recargos($datos);
846
        $this->normalizar_agregar_IVA_MntTotal($datos);
847
    }
848
849
    /**
850
     * Método que normaliza los datos de una factura de compra electrónica
851
     * @param datos Arreglo con los datos del documento que se desean normalizar
852
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
853
     * @version 2016-02-26
854
     */
855
    private function normalizar_46(array &$datos)
856
    {
857
        // completar con nodos por defecto
858
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
859
            'Encabezado' => [
860
                'IdDoc' => false,
861
                'Emisor' => false,
862
                'Receptor' => false,
863
                'RUTSolicita' => false,
864
                'Totales' => [
865
                    'MntNeto' => 0,
866
                    'MntExe' => false,
867
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
868
                    'IVA' => 0,
869
                    'ImptoReten' => false,
870
                    'IVANoRet' => false,
871
                    'MntTotal' => 0,
872
                ]
873
            ],
874
        ], $datos);
875
        // normalizar datos
876
        $this->normalizar_detalle($datos);
877
        $this->normalizar_aplicar_descuentos_recargos($datos);
878
        $this->normalizar_impuesto_retenido($datos);
879
        $this->normalizar_agregar_IVA_MntTotal($datos);
880
    }
881
882
    /**
883
     * Método que normaliza los datos de una guía de despacho electrónica
884
     * @param datos Arreglo con los datos del documento que se desean normalizar
885
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
886
     * @version 2017-07-24
887
     */
888
    private function normalizar_52(array &$datos)
889
    {
890
        // completar con nodos por defecto
891
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
892
            'Encabezado' => [
893
                'IdDoc' => false,
894
                'Emisor' => false,
895
                'Receptor' => false,
896
                'RUTSolicita' => false,
897
                'Transporte' => false,
898
                'Totales' => [
899
                    'MntNeto' => 0,
900
                    'MntExe' => false,
901
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
902
                    'IVA' => 0,
903
                    'ImptoReten' => false,
904
                    'CredEC' => false,
905
                    'MntTotal' => 0,
906
                ]
907
            ],
908
        ], $datos);
909
        // si es traslado interno se copia el emisor en el receptor sólo si el
910
        // receptor no está definido o bien si el receptor tiene RUT diferente
911
        // al emisor
912
        if ($datos['Encabezado']['IdDoc']['IndTraslado']==5) {
913
            if (!$datos['Encabezado']['Receptor'] or $datos['Encabezado']['Receptor']['RUTRecep']!=$datos['Encabezado']['Emisor']['RUTEmisor']) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
914
                $datos['Encabezado']['Receptor'] = [];
915
                $cols = [
916
                    'RUTEmisor'=>'RUTRecep',
917
                    'RznSoc'=>'RznSocRecep',
918
                    'GiroEmis'=>'GiroRecep',
919
                    'Telefono'=>'Contacto',
920
                    'CorreoEmisor'=>'CorreoRecep',
921
                    'DirOrigen'=>'DirRecep',
922
                    'CmnaOrigen'=>'CmnaRecep',
923
                ];
924
                foreach ($cols as $emisor => $receptor) {
925
                    if (!empty($datos['Encabezado']['Emisor'][$emisor])) {
926
                        $datos['Encabezado']['Receptor'][$receptor] = $datos['Encabezado']['Emisor'][$emisor];
927
                    }
928
                }
929 View Code Duplication
                if (!empty($datos['Encabezado']['Receptor']['GiroRecep'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
930
                    $datos['Encabezado']['Receptor']['GiroRecep'] = mb_substr($datos['Encabezado']['Receptor']['GiroRecep'], 0, 40);
931
                }
932
            }
933
        }
934
        // normalizar datos
935
        $this->normalizar_detalle($datos);
936
        $this->normalizar_aplicar_descuentos_recargos($datos);
937
        $this->normalizar_impuesto_retenido($datos);
938
        $this->normalizar_agregar_IVA_MntTotal($datos);
939
    }
940
941
    /**
942
     * Método que normaliza los datos de una nota de débito
943
     * @param datos Arreglo con los datos del documento que se desean normalizar
944
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
945
     * @version 2017-02-23
946
     */
947 View Code Duplication
    private function normalizar_56(array &$datos)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
948
    {
949
        // completar con nodos por defecto
950
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
951
            'Encabezado' => [
952
                'IdDoc' => false,
953
                'Emisor' => false,
954
                'Receptor' => false,
955
                'RUTSolicita' => false,
956
                'Totales' => [
957
                    'MntNeto' => 0,
958
                    'MntExe' => 0,
959
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
960
                    'IVA' => false,
961
                    'ImptoReten' => false,
962
                    'IVANoRet' => false,
963
                    'CredEC' => false,
964
                    'MntTotal' => 0,
965
                ]
966
            ],
967
        ], $datos);
968
        // normalizar datos
969
        $this->normalizar_detalle($datos);
970
        $this->normalizar_aplicar_descuentos_recargos($datos);
971
        $this->normalizar_impuesto_retenido($datos);
972
        $this->normalizar_agregar_IVA_MntTotal($datos);
973
        if (!$datos['Encabezado']['Totales']['MntNeto']) {
974
            $datos['Encabezado']['Totales']['MntNeto'] = 0;
975
            $datos['Encabezado']['Totales']['TasaIVA'] = false;
976
        }
977
    }
978
979
    /**
980
     * Método que normaliza los datos de una nota de crédito
981
     * @param datos Arreglo con los datos del documento que se desean normalizar
982
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
983
     * @version 2017-02-23
984
     */
985 View Code Duplication
    private function normalizar_61(array &$datos)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
986
    {
987
        // completar con nodos por defecto
988
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
989
            'Encabezado' => [
990
                'IdDoc' => false,
991
                'Emisor' => false,
992
                'Receptor' => false,
993
                'RUTSolicita' => false,
994
                'Totales' => [
995
                    'MntNeto' => 0,
996
                    'MntExe' => 0,
997
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
998
                    'IVA' => false,
999
                    'ImptoReten' => false,
1000
                    'IVANoRet' => false,
1001
                    'CredEC' => false,
1002
                    'MntTotal' => 0,
1003
                ]
1004
            ],
1005
        ], $datos);
1006
        // normalizar datos
1007
        $this->normalizar_detalle($datos);
1008
        $this->normalizar_aplicar_descuentos_recargos($datos);
1009
        $this->normalizar_impuesto_retenido($datos);
1010
        $this->normalizar_agregar_IVA_MntTotal($datos);
1011
        if (!$datos['Encabezado']['Totales']['MntNeto']) {
1012
            $datos['Encabezado']['Totales']['MntNeto'] = 0;
1013
            $datos['Encabezado']['Totales']['TasaIVA'] = false;
1014
        }
1015
    }
1016
1017
    /**
1018
     * Método que normaliza los datos de una factura electrónica de exportación
1019
     * @param datos Arreglo con los datos del documento que se desean normalizar
1020
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1021
     * @version 2016-04-05
1022
     */
1023 View Code Duplication
    private function normalizar_110(array &$datos)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1024
    {
1025
        // completar con nodos por defecto
1026
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1027
            'Encabezado' => [
1028
                'IdDoc' => false,
1029
                'Emisor' => false,
1030
                'Receptor' => false,
1031
                'Transporte' => [
1032
                    'Patente' => false,
1033
                    'RUTTrans' => false,
1034
                    'Chofer' => false,
1035
                    'DirDest' => false,
1036
                    'CmnaDest' => false,
1037
                    'CiudadDest' => false,
1038
                    'Aduana' => [
1039
                        'CodModVenta' => false,
1040
                        'CodClauVenta' => false,
1041
                        'TotClauVenta' => false,
1042
                        'CodViaTransp' => false,
1043
                        'NombreTransp' => false,
1044
                        'RUTCiaTransp' => false,
1045
                        'NomCiaTransp' => false,
1046
                        'IdAdicTransp' => false,
1047
                        'Booking' => false,
1048
                        'Operador' => false,
1049
                        'CodPtoEmbarque' => false,
1050
                        'IdAdicPtoEmb' => false,
1051
                        'CodPtoDesemb' => false,
1052
                        'IdAdicPtoDesemb' => false,
1053
                        'Tara' => false,
1054
                        'CodUnidMedTara' => false,
1055
                        'PesoBruto' => false,
1056
                        'CodUnidPesoBruto' => false,
1057
                        'PesoNeto' => false,
1058
                        'CodUnidPesoNeto' => false,
1059
                        'TotItems' => false,
1060
                        'TotBultos' => false,
1061
                        'TipoBultos' => false,
1062
                        'MntFlete' => false,
1063
                        'MntSeguro' => false,
1064
                        'CodPaisRecep' => false,
1065
                        'CodPaisDestin' => false,
1066
                    ],
1067
                ],
1068
                'Totales' => [
1069
                    'TpoMoneda' => null,
1070
                    'MntExe' => 0,
1071
                    'MntTotal' => 0,
1072
                ]
1073
            ],
1074
        ], $datos);
1075
        // normalizar datos
1076
        $this->normalizar_detalle($datos);
1077
        $this->normalizar_aplicar_descuentos_recargos($datos);
1078
        $this->normalizar_impuesto_retenido($datos);
1079
        $this->normalizar_agregar_IVA_MntTotal($datos);
1080
        $this->normalizar_exportacion($datos);
1081
    }
1082
1083
    /**
1084
     * Método que normaliza los datos de una nota de débito de exportación
1085
     * @param datos Arreglo con los datos del documento que se desean normalizar
1086
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1087
     * @version 2016-04-05
1088
     */
1089 View Code Duplication
    private function normalizar_111(array &$datos)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1090
    {
1091
        // completar con nodos por defecto
1092
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1093
            'Encabezado' => [
1094
                'IdDoc' => false,
1095
                'Emisor' => false,
1096
                'Receptor' => false,
1097
                'Transporte' => [
1098
                    'Patente' => false,
1099
                    'RUTTrans' => false,
1100
                    'Chofer' => false,
1101
                    'DirDest' => false,
1102
                    'CmnaDest' => false,
1103
                    'CiudadDest' => false,
1104
                    'Aduana' => [
1105
                        'CodModVenta' => false,
1106
                        'CodClauVenta' => false,
1107
                        'TotClauVenta' => false,
1108
                        'CodViaTransp' => false,
1109
                        'NombreTransp' => false,
1110
                        'RUTCiaTransp' => false,
1111
                        'NomCiaTransp' => false,
1112
                        'IdAdicTransp' => false,
1113
                        'Booking' => false,
1114
                        'Operador' => false,
1115
                        'CodPtoEmbarque' => false,
1116
                        'IdAdicPtoEmb' => false,
1117
                        'CodPtoDesemb' => false,
1118
                        'IdAdicPtoDesemb' => false,
1119
                        'Tara' => false,
1120
                        'CodUnidMedTara' => false,
1121
                        'PesoBruto' => false,
1122
                        'CodUnidPesoBruto' => false,
1123
                        'PesoNeto' => false,
1124
                        'CodUnidPesoNeto' => false,
1125
                        'TotItems' => false,
1126
                        'TotBultos' => false,
1127
                        'TipoBultos' => false,
1128
                        'MntFlete' => false,
1129
                        'MntSeguro' => false,
1130
                        'CodPaisRecep' => false,
1131
                        'CodPaisDestin' => false,
1132
                    ],
1133
                ],
1134
                'Totales' => [
1135
                    'TpoMoneda' => null,
1136
                    'MntExe' => 0,
1137
                    'MntTotal' => 0,
1138
                ]
1139
            ],
1140
        ], $datos);
1141
        // normalizar datos
1142
        $this->normalizar_detalle($datos);
1143
        $this->normalizar_aplicar_descuentos_recargos($datos);
1144
        $this->normalizar_impuesto_retenido($datos);
1145
        $this->normalizar_agregar_IVA_MntTotal($datos);
1146
        $this->normalizar_exportacion($datos);
1147
    }
1148
1149
    /**
1150
     * Método que normaliza los datos de una nota de crédito de exportación
1151
     * @param datos Arreglo con los datos del documento que se desean normalizar
1152
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1153
     * @version 2016-04-05
1154
     */
1155 View Code Duplication
    private function normalizar_112(array &$datos)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1156
    {
1157
        // completar con nodos por defecto
1158
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1159
            'Encabezado' => [
1160
                'IdDoc' => false,
1161
                'Emisor' => false,
1162
                'Receptor' => false,
1163
                'Transporte' => [
1164
                    'Patente' => false,
1165
                    'RUTTrans' => false,
1166
                    'Chofer' => false,
1167
                    'DirDest' => false,
1168
                    'CmnaDest' => false,
1169
                    'CiudadDest' => false,
1170
                    'Aduana' => [
1171
                        'CodModVenta' => false,
1172
                        'CodClauVenta' => false,
1173
                        'TotClauVenta' => false,
1174
                        'CodViaTransp' => false,
1175
                        'NombreTransp' => false,
1176
                        'RUTCiaTransp' => false,
1177
                        'NomCiaTransp' => false,
1178
                        'IdAdicTransp' => false,
1179
                        'Booking' => false,
1180
                        'Operador' => false,
1181
                        'CodPtoEmbarque' => false,
1182
                        'IdAdicPtoEmb' => false,
1183
                        'CodPtoDesemb' => false,
1184
                        'IdAdicPtoDesemb' => false,
1185
                        'Tara' => false,
1186
                        'CodUnidMedTara' => false,
1187
                        'PesoBruto' => false,
1188
                        'CodUnidPesoBruto' => false,
1189
                        'PesoNeto' => false,
1190
                        'CodUnidPesoNeto' => false,
1191
                        'TotItems' => false,
1192
                        'TotBultos' => false,
1193
                        'TipoBultos' => false,
1194
                        'MntFlete' => false,
1195
                        'MntSeguro' => false,
1196
                        'CodPaisRecep' => false,
1197
                        'CodPaisDestin' => false,
1198
                    ],
1199
                ],
1200
                'Totales' => [
1201
                    'TpoMoneda' => null,
1202
                    'MntExe' => 0,
1203
                    'MntTotal' => 0,
1204
                ]
1205
            ],
1206
        ], $datos);
1207
        // normalizar datos
1208
        $this->normalizar_detalle($datos);
1209
        $this->normalizar_aplicar_descuentos_recargos($datos);
1210
        $this->normalizar_impuesto_retenido($datos);
1211
        $this->normalizar_agregar_IVA_MntTotal($datos);
1212
        $this->normalizar_exportacion($datos);
1213
    }
1214
1215
    /**
1216
     * Método que normaliza los datos de exportacion de un documento
1217
     * @param datos Arreglo con los datos del documento que se desean normalizar
1218
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1219
     * @version 2016-04-04
1220
     */
1221
    public function normalizar_exportacion(array &$datos)
1222
    {
1223
        // agregar modalidad de venta por defecto si no existe
1224
        if (empty($datos['Encabezado']['Transporte']['Aduana']['CodModVenta']) and (!isset($datos['Encabezado']['IdDoc']['IndServicio']) or !in_array($datos['Encabezado']['IdDoc']['IndServicio'], [3, 4, 5]))) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1225
            $datos['Encabezado']['Transporte']['Aduana']['CodModVenta'] = 1;
1226
        }
1227
        // quitar campos que no son parte del documento de exportacion
1228
        $datos['Encabezado']['Receptor']['CmnaRecep'] = false;
1229
    }
1230
1231
    /**
1232
     * Método que normaliza los detalles del documento
1233
     * @param datos Arreglo con los datos del documento que se desean normalizar
1234
     * @warning Revisar como se aplican descuentos y recargos, ¿debería ser un porcentaje del monto original?
1235
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1236
     * @version 2017-07-24
1237
     */
1238
    private function normalizar_detalle(array &$datos)
1239
    {
1240
        if (!isset($datos['Detalle'][0]))
1241
            $datos['Detalle'] = [$datos['Detalle']];
1242
        $item = 1;
1243
        foreach ($datos['Detalle'] as &$d) {
1244
            $d = array_merge([
1245
                'NroLinDet' => $item++,
1246
                'CdgItem' => false,
1247
                'IndExe' => false,
1248
                'Retenedor' => false,
1249
                'NmbItem' => false,
1250
                'DscItem' => false,
1251
                'QtyRef' => false,
1252
                'UnmdRef' => false,
1253
                'PrcRef' => false,
1254
                'QtyItem' => false,
1255
                'UnmdItem' => false,
1256
                'PrcItem' => false,
1257
                'DescuentoPct' => false,
1258
                'DescuentoMonto' => false,
1259
                'RecargoPct' => false,
1260
                'RecargoMonto' => false,
1261
                'CodImpAdic' => false,
1262
                'MontoItem' => false,
1263
            ], $d);
1264
            // corregir datos
1265
            $d['NmbItem'] = mb_substr($d['NmbItem'], 0, 80);
1266
            if (!empty($d['DscItem'])) {
1267
                $d['DscItem'] = mb_substr($d['DscItem'], 0, 1000);
1268
            }
1269
            // normalizar
1270
            if ($this->esExportacion()) {
1271
                $d['IndExe'] = 1;
1272
            }
1273
            if (is_array($d['CdgItem'])) {
1274
                $d['CdgItem'] = array_merge([
1275
                    'TpoCodigo' => false,
1276
                    'VlrCodigo' => false,
1277
                ], $d['CdgItem']);
1278
                if ($d['Retenedor']===false and $d['CdgItem']['TpoCodigo']=='CPCS') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1279
                    $d['Retenedor'] = true;
1280
                }
1281
            }
1282
            if ($d['Retenedor']!==false) {
1283
                if (!is_array($d['Retenedor'])) {
1284
                    $d['Retenedor'] = ['IndAgente'=>'R'];
1285
                }
1286
                $d['Retenedor'] = array_merge([
1287
                    'IndAgente' => 'R',
1288
                    'MntBaseFaena' => false,
1289
                    'MntMargComer' => false,
1290
                    'PrcConsFinal' => false,
1291
                ], $d['Retenedor']);
1292
            }
1293
            if ($d['CdgItem']!==false and !is_array($d['CdgItem'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1294
                $d['CdgItem'] = [
1295
                    'TpoCodigo' => empty($d['Retenedor']['IndAgente']) ? 'INT1' : 'CPCS',
1296
                    'VlrCodigo' => $d['CdgItem'],
1297
                ];
1298
            }
1299
            if ($d['PrcItem']) {
1300
                if (!$d['QtyItem'])
1301
                    $d['QtyItem'] = 1;
1302
                if (empty($d['MontoItem'])) {
1303
                    $d['MontoItem'] = $this->round(
1304
                        $d['QtyItem'] * $d['PrcItem'],
0 ignored issues
show
Documentation introduced by
$d['QtyItem'] * $d['PrcItem'] is of type integer|double, but the function expects a object<sasco\LibreDTE\Sii\Valor>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1305
                        $datos['Encabezado']['Totales']['TpoMoneda']
1306
                    );
1307
                    // aplicar descuento
1308
                    if ($d['DescuentoPct']) {
1309
                        $d['DescuentoMonto'] = round($d['MontoItem'] * (int)$d['DescuentoPct']/100);
1310
                    }
1311
                    $d['MontoItem'] -= $d['DescuentoMonto'];
1312
                    // aplicar recargo
1313
                    if ($d['RecargoPct']) {
1314
                        $d['RecargoMonto'] = round($d['MontoItem'] * (int)$d['RecargoPct']/100);
1315
                    }
1316
                    $d['MontoItem'] += $d['RecargoMonto'];
1317
                    // aproximar monto del item
1318
                    $d['MontoItem'] = $this->round(
1319
                        $d['MontoItem'], $datos['Encabezado']['Totales']['TpoMoneda']
1320
                    );
1321
                }
1322
            } else if (empty($d['MontoItem'])) {
1323
                $d['MontoItem'] = 0;
1324
            }
1325
            // sumar valor del monto a MntNeto o MntExe según corresponda
1326
            if ($d['MontoItem']) {
1327
                // si no es boleta
1328
                if (!$this->esBoleta()) {
1329
                    if ((!isset($datos['Encabezado']['Totales']['MntNeto']) or $datos['Encabezado']['Totales']['MntNeto']===false) and isset($datos['Encabezado']['Totales']['MntExe'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1330
                        $datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
1331 View Code Duplication
                    } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1332
                        if (!empty($d['IndExe'])) {
1333
                            if ($d['IndExe']==1) {
1334
                                $datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
1335
                            }
1336
                        } else {
1337
                            $datos['Encabezado']['Totales']['MntNeto'] += $d['MontoItem'];
1338
                        }
1339
                    }
1340
                }
1341
                // si es boleta
1342 View Code Duplication
                else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1343
                    // si es exento
1344
                    if (!empty($d['IndExe'])) {
1345
                        if ($d['IndExe']==1) {
1346
                            $datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
1347
                        }
1348
                    }
1349
                    // agregar al monto total
1350
                    $datos['Encabezado']['Totales']['MntTotal'] += $d['MontoItem'];
1351
                }
1352
            }
1353
        }
1354
    }
1355
1356
    /**
1357
     * Método que aplica los descuentos y recargos generales respectivos a los
1358
     * montos que correspondan según e indicador del descuento o recargo
1359
     * @param datos Arreglo con los datos del documento que se desean normalizar
1360
     * @warning Boleta afecta con algún item exento el descuento se podría estar aplicando mal
1361
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1362
     * @version 2016-10-18
1363
     */
1364
    private function normalizar_aplicar_descuentos_recargos(array &$datos)
1365
    {
1366
        if (!empty($datos['DscRcgGlobal'])) {
1367 View Code Duplication
            if (!isset($datos['DscRcgGlobal'][0]))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1368
                $datos['DscRcgGlobal'] = [$datos['DscRcgGlobal']];
1369
            foreach ($datos['DscRcgGlobal'] as $dr) {
1370
                $dr = array_merge([
1371
                    'NroLinDR' => false,
1372
                    'TpoMov' => false,
1373
                    'GlosaDR' => false,
1374
                    'TpoValor' => false,
1375
                    'ValorDR' => false,
1376
                    'ValorDROtrMnda' => false,
1377
                    'IndExeDR' => false,
1378
                ], $dr);
1379
                if ($this->esExportacion()) {
1380
                    $dr['IndExeDR'] = 1;
1381
                }
1382
                // determinar a que aplicar el descuento/recargo
1383
                if (!isset($dr['IndExeDR']) or $dr['IndExeDR']===false)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1384
                    $monto = $this->getTipo()==39 ? 'MntTotal' : 'MntNeto';
1385
                else if ($dr['IndExeDR']==1)
1386
                    $monto = 'MntExe';
1387
                else if ($dr['IndExeDR']==2)
1388
                    $monto = 'MontoNF';
1389
                // si no hay monto al que aplicar el descuento se omite
1390
                if (empty($datos['Encabezado']['Totales'][$monto]))
1391
                    continue;
1392
                // calcular valor del descuento o recargo
1393
                if ($dr['TpoValor']=='$')
1394
                    $dr['ValorDR'] = $this->round($dr['ValorDR'], $datos['Encabezado']['Totales']['TpoMoneda'], 2);
1395
                $valor =
1396
                    $dr['TpoValor']=='%'
1397
                    ? $this->round(($dr['ValorDR']/100)*$datos['Encabezado']['Totales'][$monto], $datos['Encabezado']['Totales']['TpoMoneda'])
0 ignored issues
show
Bug introduced by
The variable $monto 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...
Documentation introduced by
$dr['ValorDR'] / 100 * $...do']['Totales'][$monto] is of type integer|double, but the function expects a object<sasco\LibreDTE\Sii\Valor>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1398
                    : $dr['ValorDR']
1399
                ;
1400
                // aplicar descuento
1401
                if ($dr['TpoMov']=='D') {
1402
                    $datos['Encabezado']['Totales'][$monto] -= $valor;
1403
                }
1404
                // aplicar recargo
1405
                else if ($dr['TpoMov']=='R') {
1406
                    $datos['Encabezado']['Totales'][$monto] += $valor;
1407
                }
1408
                $datos['Encabezado']['Totales'][$monto] = $this->round(
1409
                    $datos['Encabezado']['Totales'][$monto],
1410
                    $datos['Encabezado']['Totales']['TpoMoneda']
1411
                );
1412
                // si el descuento global se aplica a una boleta exenta se copia el valor exento al total
1413
                if ($this->getTipo()==41 and isset($dr['IndExeDR']) and $dr['IndExeDR']==1) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1414
                    $datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntExe'];
1415
                }
1416
            }
1417
        }
1418
    }
1419
1420
    /**
1421
     * Método que calcula los montos de impuestos adicionales o retenciones
1422
     * @param datos Arreglo con los datos del documento que se desean normalizar
1423
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1424
     * @version 2016-04-05
1425
     */
1426
    private function normalizar_impuesto_retenido(array &$datos)
1427
    {
1428
        // copiar montos
1429
        $montos = [];
1430
        foreach ($datos['Detalle'] as &$d) {
1431
            if (!empty($d['CodImpAdic'])) {
1432
                if (!isset($montos[$d['CodImpAdic']]))
1433
                    $montos[$d['CodImpAdic']] = 0;
1434
                $montos[$d['CodImpAdic']] += $d['MontoItem'];
1435
            }
1436
        }
1437
        // si hay montos y no hay total para impuesto retenido se arma
1438
        if (!empty($montos)) {
1439 View Code Duplication
            if (!is_array($datos['Encabezado']['Totales']['ImptoReten'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1440
                $datos['Encabezado']['Totales']['ImptoReten'] = [];
1441
            } else if (!isset($datos['Encabezado']['Totales']['ImptoReten'][0])) {
1442
                $datos['Encabezado']['Totales']['ImptoReten'] = [$datos['Encabezado']['Totales']['ImptoReten']];
1443
            }
1444
        }
1445
        // armar impuesto adicional o retención en los totales
1446
        foreach ($montos as $codigo => $neto) {
1447
            // buscar si existe el impuesto en los totales
1448
            $i = 0;
1449
            foreach ($datos['Encabezado']['Totales']['ImptoReten'] as &$ImptoReten) {
1450
                if ($ImptoReten['TipoImp']==$codigo) {
1451
                    break;
1452
                }
1453
                $i++;
1454
            }
1455
            // si no existe se crea
1456 View Code Duplication
            if (!isset($datos['Encabezado']['Totales']['ImptoReten'][$i])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1457
                $datos['Encabezado']['Totales']['ImptoReten'][] = [
1458
                    'TipoImp' => $codigo
1459
                ];
1460
            }
1461
            // se normaliza
1462
            $datos['Encabezado']['Totales']['ImptoReten'][$i] = array_merge([
1463
                'TipoImp' => $codigo,
1464
                'TasaImp' => ImpuestosAdicionales::getTasa($codigo),
1465
                'MontoImp' => null,
1466
            ], $datos['Encabezado']['Totales']['ImptoReten'][$i]);
1467
            // si el monto no existe se asigna
1468
            if ($datos['Encabezado']['Totales']['ImptoReten'][$i]['MontoImp']===null) {
1469
                $datos['Encabezado']['Totales']['ImptoReten'][$i]['MontoImp'] = round(
1470
                    $neto * $datos['Encabezado']['Totales']['ImptoReten'][$i]['TasaImp']/100
1471
                );
1472
            }
1473
        }
1474
        // quitar los codigos que no existen en el detalle
1475
        if (isset($datos['Encabezado']['Totales']['ImptoReten']) and is_array($datos['Encabezado']['Totales']['ImptoReten'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1476
            $codigos = array_keys($montos);
1477
            $n_impuestos = count($datos['Encabezado']['Totales']['ImptoReten']);
1478
            for ($i=0; $i<$n_impuestos; $i++) {
1479 View Code Duplication
                if (!in_array($datos['Encabezado']['Totales']['ImptoReten'][$i]['TipoImp'], $codigos)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1480
                    unset($datos['Encabezado']['Totales']['ImptoReten'][$i]);
1481
                }
1482
            }
1483
            sort($datos['Encabezado']['Totales']['ImptoReten']);
1484
        }
1485
    }
1486
1487
    /**
1488
     * Método que calcula el monto del IVA y el monto total del documento a
1489
     * partir del monto neto y la tasa de IVA si es que existe
1490
     * @param datos Arreglo con los datos del documento que se desean normalizar
1491
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1492
     * @version 2016-04-05
1493
     */
1494
    private function normalizar_agregar_IVA_MntTotal(array &$datos)
1495
    {
1496
        // agregar IVA y monto total
1497
        if (!empty($datos['Encabezado']['Totales']['MntNeto'])) {
1498
            if ($datos['Encabezado']['IdDoc']['MntBruto']==1) {
1499
                list($datos['Encabezado']['Totales']['MntNeto'], $datos['Encabezado']['Totales']['IVA']) = $this->calcularNetoIVA(
1500
                    $datos['Encabezado']['Totales']['MntNeto'],
1501
                    $datos['Encabezado']['Totales']['TasaIVA']
1502
                );
1503
            } else {
1504
                if (empty($datos['Encabezado']['Totales']['IVA']) and !empty($datos['Encabezado']['Totales']['TasaIVA'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1505
                    $datos['Encabezado']['Totales']['IVA'] = round(
1506
                        $datos['Encabezado']['Totales']['MntNeto']*($datos['Encabezado']['Totales']['TasaIVA']/100)
1507
                    );
1508
                }
1509
            }
1510
            if (empty($datos['Encabezado']['Totales']['MntTotal'])) {
1511
                $datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntNeto'];
1512
                if (!empty($datos['Encabezado']['Totales']['IVA']))
1513
                    $datos['Encabezado']['Totales']['MntTotal'] += $datos['Encabezado']['Totales']['IVA'];
1514
                if (!empty($datos['Encabezado']['Totales']['MntExe']))
1515
                    $datos['Encabezado']['Totales']['MntTotal'] += $datos['Encabezado']['Totales']['MntExe'];
1516
            }
1517 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1518
            if (!$datos['Encabezado']['Totales']['MntTotal'] and !empty($datos['Encabezado']['Totales']['MntExe'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1519
                $datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntExe'];
1520
            }
1521
        }
1522
        // si hay impuesto retenido o adicional se contabiliza en el total
1523
        if (!empty($datos['Encabezado']['Totales']['ImptoReten'])) {
1524
            foreach ($datos['Encabezado']['Totales']['ImptoReten'] as &$ImptoReten) {
1525
                // si es retención se resta al total y se traspasaa IVA no retenido
1526
                // en caso que corresponda
1527
                if (ImpuestosAdicionales::getTipo($ImptoReten['TipoImp'])=='R') {
1528
                    $datos['Encabezado']['Totales']['MntTotal'] -= $ImptoReten['MontoImp'];
1529
                    if ($ImptoReten['MontoImp']!=$datos['Encabezado']['Totales']['IVA']) {
1530
                        $datos['Encabezado']['Totales']['IVANoRet'] = $datos['Encabezado']['Totales']['IVA'] - $ImptoReten['MontoImp'];
1531
                    }
1532
                }
1533
                // si es adicional se suma al total
1534
                else if (ImpuestosAdicionales::getTipo($ImptoReten['TipoImp'])=='A' and isset($ImptoReten['MontoImp'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1535
                    $datos['Encabezado']['Totales']['MntTotal'] += $ImptoReten['MontoImp'];
1536
                }
1537
            }
1538
        }
1539
        // si hay impuesto de crédito a constructoras del 65% se descuenta del total
1540
        if (!empty($datos['Encabezado']['Totales']['CredEC'])) {
1541
            if ($datos['Encabezado']['Totales']['CredEC']===true)
1542
                $datos['Encabezado']['Totales']['CredEC'] = round($datos['Encabezado']['Totales']['IVA'] * 0.65); // TODO: mover a constante o método
1543
            $datos['Encabezado']['Totales']['MntTotal'] -= $datos['Encabezado']['Totales']['CredEC'];
1544
        }
1545
    }
1546
1547
    /**
1548
     * Método que normaliza las boletas electrónicas, dte 39 y 41
1549
     * @param datos Arreglo con los datos del documento que se desean normalizar
1550
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1551
     * @version 2017-08-17
1552
     */
1553
    private function normalizar_boletas(array &$datos)
1554
    {
1555
        // cambiar tags de DTE a boleta si se pasaron
1556 View Code Duplication
        if ($datos['Encabezado']['Emisor']['RznSoc']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1557
            $datos['Encabezado']['Emisor']['RznSocEmisor'] = $datos['Encabezado']['Emisor']['RznSoc'];
1558
            $datos['Encabezado']['Emisor']['RznSoc'] = false;
1559
        }
1560 View Code Duplication
        if ($datos['Encabezado']['Emisor']['GiroEmis']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1561
            $datos['Encabezado']['Emisor']['GiroEmisor'] = $datos['Encabezado']['Emisor']['GiroEmis'];
1562
            $datos['Encabezado']['Emisor']['GiroEmis'] = false;
1563
        }
1564
        $datos['Encabezado']['Emisor']['Acteco'] = false;
1565
        $datos['Encabezado']['Emisor']['Telefono'] = false;
1566
        $datos['Encabezado']['Emisor']['CorreoEmisor'] = false;
1567
        $datos['Encabezado']['Emisor']['CdgVendedor'] = false;
1568
        $datos['Encabezado']['Receptor']['GiroRecep'] = false;
1569
        $datos['Encabezado']['Receptor']['CorreoRecep'] = false;
1570
        // quitar otros tags que no son parte de las boletas
1571
        $datos['Encabezado']['IdDoc']['FmaPago'] = false;
1572
        $datos['Encabezado']['IdDoc']['FchCancel'] = false;
1573
        $datos['Encabezado']['IdDoc']['TermPagoGlosa'] = false;
1574
        $datos['Encabezado']['RUTSolicita'] = false;
1575
        // si es boleta no nominativa se deja sólo el RUT en el campo del receptor
1576
        if ($datos['Encabezado']['Receptor']['RUTRecep']=='66666666-6') {
1577
            $datos['Encabezado']['Receptor'] = ['RUTRecep'=>'66666666-6'];
1578
        }
1579
        // ajustar las referencias si existen
1580
        if (!empty($datos['Referencia'])) {
1581 View Code Duplication
            if (!isset($datos['Referencia'][0])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1582
                $datos['Referencia'] = [$datos['Referencia']];
1583
            }
1584
            foreach ($datos['Referencia'] as &$r) {
1585
                foreach (['TpoDocRef', 'FolioRef', 'FchRef'] as $c) {
1586
                    if (isset($r[$c])) {
1587
                        unset($r[$c]);
1588
                    }
1589
                }
1590
            }
1591
        }
1592
    }
1593
1594
    /**
1595
     * Método que redondea valores. Si los montos son en pesos chilenos se
1596
     * redondea, si no se mantienen todos los decimales
1597
     * @param valor Valor que se desea redondear
1598
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1599
     * @version 2016-04-05
1600
     */
1601
    private function round($valor, $moneda = false, $decimal = 4)
1602
    {
1603
        return (!$moneda or $moneda=='PESO CL') ? (int)round($valor) : (float)round($valor, $decimal);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1604
    }
1605
1606
    /**
1607
     * Método que determina el estado de validación sobre el DTE, se verifica:
1608
     *  - Firma del DTE
1609
     *  - RUT del emisor (si se pasó uno para comparar)
1610
     *  - RUT del receptor (si se pasó uno para comparar)
1611
     * @return Código del estado de la validación
1612
     * @warning No se está validando la firma
1613
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1614
     * @version 2015-09-08
1615
     */
1616
    public function getEstadoValidacion(array $datos = null)
1617
    {
1618
        /*if (!$this->checkFirma())
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1619
            return 1;*/
1620
        if (is_array($datos)) {
1621
            if (isset($datos['RUTEmisor']) and $this->getEmisor()!=$datos['RUTEmisor'])
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1622
                return 2;
1623
            if (isset($datos['RUTRecep']) and $this->getReceptor()!=$datos['RUTRecep'])
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
1624
                return 3;
1625
        }
1626
        return 0;
1627
    }
1628
1629
    /**
1630
     * Método que indica si la firma del DTE es o no válida
1631
     * @return =true si la firma del DTE es válida, =null si no se pudo determinar
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1632
     * @warning No se está verificando el valor del DigestValue del documento (sólo la firma de ese DigestValue)
1633
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1634
     * @version 2015-09-08
1635
     */
1636
    public function checkFirma()
1637
    {
1638
        if (!$this->xml)
1639
            return null;
1640
        // obtener firma
1641
        $Signature = $this->xml->documentElement->getElementsByTagName('Signature')->item(0);
1642
        // preparar documento a validar
1643
        $D = $this->xml->documentElement->getElementsByTagName('Documento')->item(0);
1644
        $Documento = new \sasco\LibreDTE\XML();
1645
        $Documento->loadXML($D->C14N());
1646
        $Documento->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
1647
        $Documento->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
1648
        $SignedInfo = new \sasco\LibreDTE\XML();
1649
        $SignedInfo->loadXML($Signature->getElementsByTagName('SignedInfo')->item(0)->C14N());
1650
        $SignedInfo->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
1651
        $DigestValue = $Signature->getElementsByTagName('DigestValue')->item(0)->nodeValue;
0 ignored issues
show
Unused Code introduced by
$DigestValue 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...
1652
        $SignatureValue = $Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue;
1653
        $X509Certificate = $Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue;
1654
        $X509Certificate = '-----BEGIN CERTIFICATE-----'."\n".wordwrap(trim($X509Certificate), 64, "\n", true)."\n".'-----END CERTIFICATE----- ';
1655
        $valid = openssl_verify($SignedInfo->C14N(), base64_decode($SignatureValue), $X509Certificate) === 1 ? true : false;
1656
        return $valid;
1657
        //return $valid and $DigestValue===base64_encode(sha1($Documento->C14N(), true));
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1658
    }
1659
1660
    /**
1661
     * Método que indica si el documento es o no cedible
1662
     * @return =true si el documento es cedible
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1663
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1664
     * @version 2015-09-10
1665
     */
1666
    public function esCedible()
1667
    {
1668
        return !in_array($this->getTipo(), $this->noCedibles);
1669
    }
1670
1671
    /**
1672
     * Método que indica si el documento es o no una boleta electrónica
1673
     * @return =true si el documento es una boleta electrónica
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1674
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1675
     * @version 2015-12-11
1676
     */
1677
    public function esBoleta()
1678
    {
1679
        return in_array($this->getTipo(), [39, 41]);
1680
    }
1681
1682
    /**
1683
     * Método que indica si el documento es o no una exportación
1684
     * @return =true si el documento es una exportación
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1685
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1686
     * @version 2016-04-05
1687
     */
1688
    public function esExportacion()
1689
    {
1690
        return in_array($this->getTipo(), $this->tipos['Exportaciones']);
1691
    }
1692
1693
    /**
1694
     * Método que valida el schema del DTE
1695
     * @return =true si el schema del documento del DTE es válido, =null si no se pudo determinar
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1696
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1697
     * @version 2015-12-15
1698
     */
1699
    public function schemaValidate()
1700
    {
1701
        return true;
1702
    }
1703
1704
    /**
1705
     * Método que valida los datos del DTE
1706
     * @return =true si el schema del documento del DTE es válido, =null si no se pudo determinar
0 ignored issues
show
Documentation introduced by
The doc-type =true could not be parsed: Unknown type name "=true" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1707
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1708
     * @version 2017-02-06
1709
     */
1710
    public function verificarDatos()
1711
    {
1712
        if (class_exists('\sasco\LibreDTE\Sii\VerificadorDatos')) {
1713
            if (!\sasco\LibreDTE\Sii\VerificadorDatos::Dte($this->getDatos())) {
1714
                return false;
1715
            }
1716
        }
1717
        return true;
1718
    }
1719
1720
    /**
1721
     * Método que obtiene el estado del DTE
1722
     * @param Firma objeto que representa la Firma Electrónca
1723
     * @return Arreglo con el estado del DTE
1724
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1725
     * @version 2015-10-24
1726
     */
1727
    public function getEstado(\sasco\LibreDTE\FirmaElectronica $Firma)
1728
    {
1729
        // solicitar token
1730
        $token = \sasco\LibreDTE\Sii\Autenticacion::getToken($Firma);
0 ignored issues
show
Documentation introduced by
$Firma is of type object<sasco\LibreDTE\FirmaElectronica>, but the function expects a object<sasco\LibreDTE\Sii\objeto>|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1731
        if (!$token)
0 ignored issues
show
Bug Best Practice introduced by
The expression $token of type false|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1732
            return false;
1733
        // consultar estado dte
1734
        $run = $Firma->getID();
1735
        if ($run===false)
1736
            return false;
1737
        list($RutConsultante, $DvConsultante) = explode('-', $run);
1738
        list($RutCompania, $DvCompania) = explode('-', $this->getEmisor());
1739
        list($RutReceptor, $DvReceptor) = explode('-', $this->getReceptor());
1740
        list($Y, $m, $d) = explode('-', $this->getFechaEmision());
1741
        $xml = \sasco\LibreDTE\Sii::request('QueryEstDte', 'getEstDte', [
0 ignored issues
show
Documentation introduced by
'QueryEstDte' is of type string, but the function expects a object<sasco\LibreDTE\Nombre>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
'getEstDte' is of type string, but the function expects a object<sasco\LibreDTE\Nombre>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
array('RutConsultante' =...l(), 'token' => $token) is of type array<string,?,{"RutCons...to>","token":"string"}>, but the function expects a object<sasco\LibreDTE\Argumentos>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1742
            'RutConsultante'    => $RutConsultante,
1743
            'DvConsultante'     => $DvConsultante,
1744
            'RutCompania'       => $RutCompania,
1745
            'DvCompania'        => $DvCompania,
1746
            'RutReceptor'       => $RutReceptor,
1747
            'DvReceptor'        => $DvReceptor,
1748
            'TipoDte'           => $this->getTipo(),
1749
            'FolioDte'          => $this->getFolio(),
1750
            'FechaEmisionDte'   => $d.$m.$Y,
1751
            'MontoDte'          => $this->getMontoTotal(),
1752
            'token'             => $token,
1753
        ]);
1754
        // si el estado se pudo recuperar se muestra
1755
        if ($xml===false)
1756
            return false;
1757
        // entregar estado
1758
        return (array)$xml->xpath('/SII:RESPUESTA/SII:RESP_HDR')[0];
1759
    }
1760
1761
    /**
1762
     * Método que obtiene el estado avanzado del DTE
1763
     * @param Firma objeto que representa la Firma Electrónca
1764
     * @return Arreglo con el estado del DTE
1765
     * @todo Corregir warning y también definir que se retornará (sobre todo en caso de error)
1766
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1767
     * @version 2016-08-05
1768
     */
1769
    public function getEstadoAvanzado(\sasco\LibreDTE\FirmaElectronica $Firma)
1770
    {
1771
        // solicitar token
1772
        $token = \sasco\LibreDTE\Sii\Autenticacion::getToken($Firma);
0 ignored issues
show
Documentation introduced by
$Firma is of type object<sasco\LibreDTE\FirmaElectronica>, but the function expects a object<sasco\LibreDTE\Sii\objeto>|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1773
        if (!$token)
0 ignored issues
show
Bug Best Practice introduced by
The expression $token of type false|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1774
            return false;
1775
        // consultar estado dte
1776
        list($RutEmpresa, $DvEmpresa) = explode('-', $this->getEmisor());
1777
        list($RutReceptor, $DvReceptor) = explode('-', $this->getReceptor());
1778
        list($Y, $m, $d) = explode('-', $this->getFechaEmision());
1779
        $xml = \sasco\LibreDTE\Sii::request('QueryEstDteAv', 'getEstDteAv', [
0 ignored issues
show
Documentation introduced by
'QueryEstDteAv' is of type string, but the function expects a object<sasco\LibreDTE\Nombre>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
'getEstDteAv' is of type string, but the function expects a object<sasco\LibreDTE\Nombre>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
array('RutEmpresa' => $R...']), 'token' => $token) is of type array<string,?,{"RutEmpr...:"?","token":"string"}>, but the function expects a object<sasco\LibreDTE\Argumentos>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1780
            'RutEmpresa'       => $RutEmpresa,
1781
            'DvEmpresa'        => $DvEmpresa,
1782
            'RutReceptor'       => $RutReceptor,
1783
            'DvReceptor'        => $DvReceptor,
1784
            'TipoDte'           => $this->getTipo(),
1785
            'FolioDte'          => $this->getFolio(),
1786
            'FechaEmisionDte'   => $d.'-'.$m.'-'.$Y,
1787
            'MontoDte'          => $this->getMontoTotal(),
1788
            'FirmaDte'          => str_replace("\n", '', $this->getFirma()['SignatureValue']),
1789
            'token'             => $token,
1790
        ]);
1791
        // si el estado se pudo recuperar se muestra
1792
        if ($xml===false)
1793
            return false;
1794
        // entregar estado
1795
        return (array)$xml->xpath('/SII:RESPUESTA/SII:RESP_BODY')[0];
1796
    }
1797
1798
}
1799