Completed
Push — master ( 910333...7a0a1e )
by Esteban De La Fuente
03:50
created

Dte::getCertificacion()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 4
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 2017-08-29
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-10-22
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], 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 ($normalizar and !$this->verificarDatos()) {
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...
145
                return false;
146
            }
147
            return $this->schemaValidate();
148
        }
149
        return false;
150
    }
151
152
    /**
153
     * Método que entrega el arreglo con los datos del DTE.
154
     * Si el DTE fue creado a partir de un arreglo serán los datos normalizados,
155
     * en cambio si se creó a partir de un XML serán todos los nodos del
156
     * documento sin cambios.
157
     * @return Arreglo con datos del DTE
158
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
159
     * @version 2016-07-04
160
     */
161
    public function getDatos()
162
    {
163
        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...
164
            $datos = $this->xml->toArray();
165
            if (!isset($datos['DTE'][$this->tipo_general])) {
166
                \sasco\LibreDTE\Log::write(
167
                    \sasco\LibreDTE\Estado::DTE_ERROR_GETDATOS,
168
                    \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...
169
                );
170
                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...
171
            }
172
            $this->datos = $datos['DTE'][$this->tipo_general];
173
            if (isset($datos['DTE']['Signature'])) {
174
                $this->Signature = $datos['DTE']['Signature'];
175
            }
176
        }
177
        return $this->datos;
178
    }
179
180
    /**
181
     * Método que entrega el arreglo con los datos de la firma del DTE
182
     * @return Arreglo con datos de la firma
183
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
184
     * @version 2016-06-11
185
     */
186
    public function getFirma()
187
    {
188
        if (!$this->Signature) {
189
            $this->getDatos();
190
        }
191
        return $this->Signature;
192
    }
193
194
    /**
195
     * Método que entrega los datos del DTE (tag Documento) como un string JSON
196
     * @return String JSON "lindo" con los datos del documento
197
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
198
     * @version 2015-09-08
199
     */
200
    public function getJSON()
201
    {
202
        if (!$this->getDatos())
203
            return false;
204
        return json_encode($this->datos, JSON_PRETTY_PRINT);
205
    }
206
207
    /**
208
     * Método que entrega el ID del documento
209
     * @return String con el ID del DTE
210
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
211
     * @version 2016-08-17
212
     */
213
    public function getID($estandar = false)
214
    {
215
        return $estandar ? ('T'.$this->tipo.'F'.$this->folio) : $this->id;
216
    }
217
218
    /**
219
     * Método que entrega el tipo general de documento, de acuerdo a
220
     * $this->tipos
221
     * @param dte Tipo númerico de DTE, ejemplo: 33 (factura electrónica)
222
     * @return String con el tipo general: Documento, Liquidacion o Exportaciones
223
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
224
     * @version 2015-09-17
225
     */
226
    private function getTipoGeneral($dte)
227
    {
228
        foreach ($this->tipos as $tipo => $codigos)
229
            if (in_array($dte, $codigos))
230
                return $tipo;
231
        \sasco\LibreDTE\Log::write(
232
            \sasco\LibreDTE\Estado::DTE_ERROR_TIPO,
233
            \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...
234
        );
235
        return false;
236
    }
237
238
    /**
239
     * Método que entrega el tipo de DTE
240
     * @return Tipo de dte, ej: 33 (factura electrónica)
241
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
242
     * @version 2015-09-02
243
     */
244
    public function getTipo()
245
    {
246
        return $this->tipo;
247
    }
248
249
    /**
250
     * Método que entrega el folio del DTE
251
     * @return Folio del DTE
252
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
253
     * @version 2015-09-02
254
     */
255
    public function getFolio()
256
    {
257
        return $this->folio;
258
    }
259
260
    /**
261
     * Método que entrega rut del emisor del DTE
262
     * @return RUT del emiro
263
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
264
     * @version 2015-09-07
265
     */
266 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...
267
    {
268
        $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...
269
        if ($nodo)
270
            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...
271
        if (!$this->getDatos())
272
            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...
273
        return $this->datos['Encabezado']['Emisor']['RUTEmisor'];
274
    }
275
276
    /**
277
     * Método que entrega rut del receptor del DTE
278
     * @return RUT del emiro
279
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
280
     * @version 2015-09-07
281
     */
282 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...
283
    {
284
        $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...
285
        if ($nodo)
286
            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...
287
        if (!$this->getDatos())
288
            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...
289
        return $this->datos['Encabezado']['Receptor']['RUTRecep'];
290
    }
291
292
    /**
293
     * Método que entrega fecha de emisión del DTE
294
     * @return Fecha de emisión en formato AAAA-MM-DD
295
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
296
     * @version 2015-09-07
297
     */
298 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...
299
    {
300
        $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...
301
        if ($nodo)
302
            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...
303
        if (!$this->getDatos())
304
            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...
305
        return $this->datos['Encabezado']['IdDoc']['FchEmis'];
306
    }
307
308
    /**
309
     * Método que entrega el monto total del DTE
310
     * @return Monto total del DTE
311
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
312
     * @version 2015-09-07
313
     */
314 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...
315
    {
316
        $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...
317
        if ($nodo)
318
            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...
319
        if (!$this->getDatos())
320
            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...
321
        return $this->datos['Encabezado']['Totales']['MntTotal'];
322
    }
323
324
    /**
325
     * Método que entrega el tipo de moneda del documento
326
     * @return String con el tipo de moneda
327
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
328
     * @version 2016-07-16
329
     */
330 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...
331
    {
332
        $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...
333
        if ($nodo)
334
            return $nodo->nodeValue;
335
        if (!$this->getDatos())
336
            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...
337
        return $this->datos['Encabezado']['Totales']['TpoMoneda'];
338
    }
339
340
    /**
341
     * Método que entrega las referencias del DTE si existen
342
     * @return Arreglo con las referencias
343
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
344
     * @version 2017-11-17
345
     */
346
    public function getReferencias()
347
    {
348
        if (!$this->getDatos()) {
349
            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::getReferencias 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...
350
        }
351
        $referencias = !empty($this->datos['Referencia']) ? $this->datos['Referencia'] : false;
352
        if (!$referencias) {
353
            return [];
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array(); (array) is incompatible with the return type documented by sasco\LibreDTE\Sii\Dte::getReferencias 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...
354
        }
355
        if (!isset($referencias[0])) {
356
            $referencias = [$referencias];
357
        }
358
        return $referencias;
359
    }
360
361
    /**
362
     * Método que entrega el string XML del tag TED
363
     * @return String XML con tag TED
364
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
365
     * @version 2016-08-03
366
     */
367
    public function getTED()
368
    {
369
        /*$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...
370
        $xml->loadXML($this->xml->getElementsByTagName('TED')->item(0)->getElementsByTagName('DD')->item(0)->C14N());
371
        $xml->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
372
        $xml->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
373
        $FRMT = $this->xml->getElementsByTagName('TED')->item(0)->getElementsByTagName('FRMT')->item(0)->nodeValue;
374
        $pub_key = '';
375
        if (openssl_verify($xml->getFlattened('/'), base64_decode($FRMT), $pub_key, OPENSSL_ALGO_SHA1)!==1);
376
            return false;*/
377
        $xml = new \sasco\LibreDTE\XML();
378
        $TED = $this->xml->getElementsByTagName('TED')->item(0);
379
        if (!$TED)
380
            return '<TED/>';
381
        $xml->loadXML($TED->C14N());
382
        $xml->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
383
        $xml->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
384
        $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...
385
        return mb_detect_encoding($TED, ['UTF-8', 'ISO-8859-1']) != 'ISO-8859-1' ? utf8_decode($TED) : $TED;
386
    }
387
388
    /**
389
     * Método que indica si el DTE es de certificación o no
390
     * @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...
391
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
392
     * @version 2016-06-15
393
     */
394
    public function getCertificacion()
395
    {
396
        $datos = $this->getDatos();
397
        $idk = !empty($datos['TED']['DD']['CAF']['DA']['IDK']) ? (int)$datos['TED']['DD']['CAF']['DA']['IDK'] : null;
398
        return $idk ? $idk === 100 : null;
399
    }
400
401
    /**
402
     * Método que realiza el timbrado del DTE
403
     * @param Folios Objeto de los Folios con los que se desea timbrar
404
     * @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...
405
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
406
     * @version 2016-09-01
407
     */
408
    public function timbrar(Folios $Folios)
409
    {
410
        // verificar que el folio que se está usando para el DTE esté dentro
411
        // del rango de folios autorizados que se usarán para timbrar
412
        // Esta validación NO verifica si el folio ya fue usado, sólo si está
413
        // dentro del CAF que se está usando
414
        $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...
415
        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...
416
            \sasco\LibreDTE\Log::write(
417
                \sasco\LibreDTE\Estado::DTE_ERROR_RANGO_FOLIO,
418
                \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...
419
            );
420
            return false;
421
        }
422
        // verificar que existan datos para el timbre
423 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...
424
            \sasco\LibreDTE\Log::write(
425
                \sasco\LibreDTE\Estado::DTE_FALTA_FCHEMIS,
426
                \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...
427
            );
428
            \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...
429
            return false;
430
        }
431 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...
432
            \sasco\LibreDTE\Log::write(
433
                \sasco\LibreDTE\Estado::DTE_FALTA_MNTTOTAL,
434
                \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...
435
            );
436
            return false;
437
        }
438
        // timbrar
439
        $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...
440
        $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...
441
        $RSR = $RSR_nodo->length ? trim(mb_substr($RSR_nodo->item(0)->nodeValue, 0, 40)) : $RR;
442
        $TED = new \sasco\LibreDTE\XML();
443
        $TED->generate([
444
            'TED' => [
445
                '@attributes' => [
446
                    'version' => '1.0',
447
                ],
448
                'DD' => [
449
                    '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...
450
                    '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...
451
                    'F' => $folio,
452
                    '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...
453
                    '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...
454
                    'RSR' => $RSR,
455
                    '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...
456
                    '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...
457
                    'CAF' => $Folios->getCaf(),
458
                    'TSTED' => $this->timestamp,
459
                ],
460
                'FRMT' => [
461
                    '@attributes' => [
462
                        'algoritmo' => 'SHA1withRSA'
463
                    ],
464
                ],
465
            ]
466
        ]);
467
        $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...
468
        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...
469
            \sasco\LibreDTE\Log::write(
470
                \sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE,
471
                \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...
472
            );
473
            return false;
474
        }
475
        $TED->getElementsByTagName('FRMT')->item(0)->nodeValue = base64_encode($timbre);
476
        $xml = str_replace('<TED/>', trim(str_replace('<?xml version="1.0" encoding="ISO-8859-1"?>', '', $TED->saveXML())), $this->saveXML());
477 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...
478
            \sasco\LibreDTE\Log::write(
479
                \sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE,
480
                \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...
481
            );
482
            return false;
483
        }
484
        return true;
485
    }
486
487
    /**
488
     * Método que realiza la firma del DTE
489
     * @param Firma objeto que representa la Firma Electrónca
490
     * @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...
491
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
492
     * @version 2017-10-22
493
     */
494
    public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
495
    {
496
        $parent = $this->xml->getElementsByTagName($this->tipo_general)->item(0);
497
        $this->xml->generate(['TmstFirma'=>$this->timestamp], 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...
498
        $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...
499 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...
500
            \sasco\LibreDTE\Log::write(
501
                \sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
502
                \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...
503
            );
504
            return false;
505
        }
506
        $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 498 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...
507
        return true;
508
    }
509
510
    /**
511
     * Método que entrega el DTE en XML
512
     * @return XML con el DTE (podría: con o sin timbre y con o sin firma)
513
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
514
     * @version 2015-08-20
515
     */
516
    public function saveXML()
517
    {
518
        return $this->xml->saveXML();
519
    }
520
521
    /**
522
     * Método que genera un arreglo con el resumen del documento. Este resumen
523
     * puede servir, por ejemplo, para generar los detalles de los IECV
524
     * @return Arreglo con el resumen del DTE
525
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
526
     * @version 2016-07-15
527
     */
528
    public function getResumen()
529
    {
530
        $this->getDatos();
531
        // generar resumen
532
        $resumen =  [
533
            'TpoDoc' => (int)$this->datos['Encabezado']['IdDoc']['TipoDTE'],
534
            'NroDoc' => (int)$this->datos['Encabezado']['IdDoc']['Folio'],
535
            'TasaImp' => 0,
536
            'FchDoc' => $this->datos['Encabezado']['IdDoc']['FchEmis'],
537
            'CdgSIISucur' => !empty($this->datos['Encabezado']['Emisor']['CdgSIISucur']) ? $this->datos['Encabezado']['Emisor']['CdgSIISucur'] : false,
538
            'RUTDoc' => $this->datos['Encabezado']['Receptor']['RUTRecep'],
539
            'RznSoc' => isset($this->datos['Encabezado']['Receptor']['RznSocRecep']) ? $this->datos['Encabezado']['Receptor']['RznSocRecep'] : false,
540
            'MntExe' => false,
541
            'MntNeto' => false,
542
            'MntIVA' => 0,
543
            'MntTotal' => 0,
544
        ];
545
        // obtener montos si es que existen en el documento
546
        $montos = ['TasaImp'=>'TasaIVA', 'MntExe'=>'MntExe', 'MntNeto'=>'MntNeto', 'MntIVA'=>'IVA', 'MntTotal'=>'MntTotal'];
547
        foreach ($montos as $dest => $orig) {
548
            if (!empty($this->datos['Encabezado']['Totales'][$orig])) {
549
                $resumen[$dest] = !$this->esExportacion() ? round($this->datos['Encabezado']['Totales'][$orig]) : $this->datos['Encabezado']['Totales'][$orig];
550
            }
551
        }
552
        // si es una boleta se calculan los datos para el resumen
553
        if ($this->esBoleta()) {
554
            if (!$resumen['TasaImp']) {
555
                $resumen['TasaImp'] = \sasco\LibreDTE\Sii::getIVA();
556
            }
557
            $resumen['MntExe'] = (int)$resumen['MntExe'];
558
            if (!$resumen['MntNeto']) {
559
                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...
560
            }
561
        }
562
        // entregar resumen
563
        return $resumen;
564
    }
565
566
    /**
567
     * Método que permite obtener el monto neto y el IVA de ese neto a partir de
568
     * un monto total
569
     * @param total neto + iva
570
     * @param tasa Tasa del IVA
571
     * @return Arreglo con el neto y el iva
572
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
573
     * @version 2016-04-05
574
     */
575
    private function calcularNetoIVA($total, $tasa = null)
576
    {
577
        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...
578
            return [0, 0];
579
        if ($tasa === null)
580
            $tasa = \sasco\LibreDTE\Sii::getIVA();
581
        // WARNING: el IVA obtenido puede no ser el NETO*(TASA/100)
582
        // se calcula el monto neto y luego se obtiene el IVA haciendo la resta
583
        // entre el total y el neto, ya que hay casos de borde como:
584
        //  - BRUTO:   680 => NETO:   571 e IVA:   108 => TOTAL:   679
585
        //  - BRUTO: 86710 => NETO: 72866 e IVA: 13845 => TOTAL: 86711
586
        $neto = round($total / (1+($tasa/100)));
587
        $iva = $total - $neto;
588
        return [$neto, $iva];
589
    }
590
591
    /**
592
     * Método que normaliza los datos de un documento tributario electrónico
593
     * @param datos Arreglo con los datos del documento que se desean normalizar
594
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
595
     * @version 2017-07-24
596
     */
597
    private function normalizar(array &$datos)
598
    {
599
        // completar con nodos por defecto
600
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
601
            'Encabezado' => [
602
                'IdDoc' => [
603
                    'TipoDTE' => false,
604
                    'Folio' => false,
605
                    'FchEmis' => date('Y-m-d'),
606
                    'IndNoRebaja' => false,
607
                    'TipoDespacho' => false,
608
                    'IndTraslado' => false,
609
                    'TpoImpresion' => false,
610
                    'IndServicio' => $this->esBoleta() ? 3 : false,
611
                    'MntBruto' => false,
612
                    'FmaPago' => false,
613
                    'FmaPagExp' => false,
614
                    'MntCancel' => false,
615
                    'SaldoInsol' => false,
616
                    'FchCancel' => false,
617
                    'MntPagos' => false,
618
                    'PeriodoDesde' => false,
619
                    'PeriodoHasta' => false,
620
                    'MedioPago' => false,
621
                    'TpoCtaPago' => false,
622
                    'NumCtaPago' => false,
623
                    'BcoPago' => false,
624
                    'TermPagoCdg' => false,
625
                    'TermPagoGlosa' => false,
626
                    'TermPagoDias' => false,
627
                    'FchVenc' => false,
628
                ],
629
                'Emisor' => [
630
                    'RUTEmisor' => false,
631
                    'RznSoc' => false,
632
                    'GiroEmis' => false,
633
                    'Telefono' => false,
634
                    'CorreoEmisor' => false,
635
                    'Acteco' => false,
636
                    'Sucursal' => false,
637
                    'CdgSIISucur' => false,
638
                    'DirOrigen' => false,
639
                    'CmnaOrigen' => false,
640
                    'CiudadOrigen' => false,
641
                    'CdgVendedor' => false,
642
                ],
643
                'Receptor' => [
644
                    'RUTRecep' => false,
645
                    'CdgIntRecep' => false,
646
                    'RznSocRecep' => false,
647
                    'Extranjero' => false,
648
                    'GiroRecep' => false,
649
                    'Contacto' => false,
650
                    'CorreoRecep' => false,
651
                    'DirRecep' => false,
652
                    'CmnaRecep' => false,
653
                    'CiudadRecep' => false,
654
                    'DirPostal' => false,
655
                    'CmnaPostal' => false,
656
                    'CiudadPostal' => false,
657
                ],
658
                'Totales' => [
659
                    'TpoMoneda' => false,
660
                ],
661
            ],
662
            'Detalle' => false,
663
            'SubTotInfo' => false,
664
            'DscRcgGlobal' => false,
665
            'Referencia' => false,
666
            'Comisiones' => false,
667
        ], $datos);
668
        // corregir algunos datos que podrían venir malos para no caer por schema
669
        $datos['Encabezado']['Emisor']['RUTEmisor'] = strtoupper($datos['Encabezado']['Emisor']['RUTEmisor']);
670
        $datos['Encabezado']['Receptor']['RUTRecep'] = strtoupper($datos['Encabezado']['Receptor']['RUTRecep']);
671
        $datos['Encabezado']['Receptor']['RznSocRecep'] = mb_substr($datos['Encabezado']['Receptor']['RznSocRecep'], 0, 100);
672 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...
673
            $datos['Encabezado']['Receptor']['GiroRecep'] = mb_substr($datos['Encabezado']['Receptor']['GiroRecep'], 0, 40);
674
        }
675 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...
676
            $datos['Encabezado']['Receptor']['Contacto'] = mb_substr($datos['Encabezado']['Receptor']['Contacto'], 0, 80);
677
        }
678 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...
679
            $datos['Encabezado']['Receptor']['CorreoRecep'] = mb_substr($datos['Encabezado']['Receptor']['CorreoRecep'], 0, 80);
680
        }
681 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...
682
            $datos['Encabezado']['Receptor']['DirRecep'] = mb_substr($datos['Encabezado']['Receptor']['DirRecep'], 0, 70);
683
        }
684 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...
685
            $datos['Encabezado']['Receptor']['CmnaRecep'] = mb_substr($datos['Encabezado']['Receptor']['CmnaRecep'], 0, 20);
686
        }
687
        // si existe descuento o recargo global se normalizan
688
        if (!empty($datos['DscRcgGlobal'])) {
689 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...
690
                $datos['DscRcgGlobal'] = [$datos['DscRcgGlobal']];
691
            $NroLinDR = 1;
692
            foreach ($datos['DscRcgGlobal'] as &$dr) {
693
                $dr = array_merge([
694
                    'NroLinDR' => $NroLinDR++,
695
                ], $dr);
696
            }
697
        }
698
        // si existe una o más referencias se normalizan
699
        if (!empty($datos['Referencia'])) {
700 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...
701
                $datos['Referencia'] = [$datos['Referencia']];
702
            }
703
            $NroLinRef = 1;
704
            foreach ($datos['Referencia'] as &$r) {
705
                $r = array_merge([
706
                    'NroLinRef' => $NroLinRef++,
707
                    'TpoDocRef' => false,
708
                    'IndGlobal' => false,
709
                    'FolioRef' => false,
710
                    'RUTOtr' => false,
711
                    'FchRef' => date('Y-m-d'),
712
                    'CodRef' => false,
713
                    'RazonRef' => false,
714
                ], $r);
715
            }
716
        }
717
    }
718
719
    /**
720
     * Método que realiza la normalización final de los datos de un documento
721
     * tributario electrónico. Esto se aplica todos los documentos una vez que
722
     * ya se aplicaron las normalizaciones por tipo
723
     * @param datos Arreglo con los datos del documento que se desean normalizar
724
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
725
     * @version 2017-09-23
726
     */
727
    private function normalizar_final(array &$datos)
728
    {
729
        // normalizar montos de pagos programados
730
        if (is_array($datos['Encabezado']['IdDoc']['MntPagos'])) {
731
            $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...
732 View Code Duplication
            if (!isset($datos['Encabezado']['IdDoc']['MntPagos'][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...
733
                $datos['Encabezado']['IdDoc']['MntPagos'] = [$datos['Encabezado']['IdDoc']['MntPagos']];
734
            }
735
            foreach ($datos['Encabezado']['IdDoc']['MntPagos'] as &$MntPagos) {
736
                $MntPagos = array_merge([
737
                    'FchPago' => null,
738
                    'MntPago' => null,
739
                    'GlosaPagos' => false,
740
                ], $MntPagos);
741
                if ($MntPagos['MntPago']===null) {
742
                    $MntPagos['MntPago'] = $datos['Encabezado']['Totales']['MntTotal'];
743
                }
744
            }
745
        }
746
        // si existe OtraMoneda se verifican los tipos de cambio y totales
747
        if (!empty($datos['Encabezado']['OtraMoneda'])) {
748 View Code Duplication
            if (!isset($datos['Encabezado']['OtraMoneda'][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...
749
                $datos['Encabezado']['OtraMoneda'] = [$datos['Encabezado']['OtraMoneda']];
750
            }
751
            foreach ($datos['Encabezado']['OtraMoneda'] as &$OtraMoneda) {
752
                // colocar campos por defecto
753
                $OtraMoneda = array_merge([
754
                    'TpoMoneda' => false,
755
                    'TpoCambio' => false,
756
                    'MntNetoOtrMnda' => false,
757
                    'MntExeOtrMnda' => false,
758
                    'MntFaeCarneOtrMnda' => false,
759
                    'MntMargComOtrMnda' => false,
760
                    'IVAOtrMnda' => false,
761
                    'ImpRetOtrMnda' => false,
762
                    'IVANoRetOtrMnda' => false,
763
                    'MntTotOtrMnda' => false,
764
                ], $OtraMoneda);
765
                // si no hay tipo de cambio no seguir
766
                if (!isset($OtraMoneda['TpoCambio'])) {
767
                    continue;
768
                }
769
                // buscar si los valores están asignados, si no lo están asignar
770
                // usando el tipo de cambio que existe para la moneda
771
                foreach (['MntNeto', 'MntExe', 'IVA', 'IVANoRet'] as $monto) {
772
                    if (empty($OtraMoneda[$monto.'OtrMnda']) and !empty($datos['Encabezado']['Totales'][$monto])) {
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...
773
                        $OtraMoneda[$monto.'OtrMnda'] = round($datos['Encabezado']['Totales'][$monto] * $OtraMoneda['TpoCambio'], 4);
774
                    }
775
                }
776
                // calcular MntFaeCarneOtrMnda, MntMargComOtrMnda, ImpRetOtrMnda
777
                if (empty($OtraMoneda['MntFaeCarneOtrMnda'])) {
778
                    $OtraMoneda['MntFaeCarneOtrMnda'] = false; // TODO
779
                }
780
                if (empty($OtraMoneda['MntMargComOtrMnda'])) {
781
                    $OtraMoneda['MntMargComOtrMnda'] = false; // TODO
782
                }
783
                if (empty($OtraMoneda['ImpRetOtrMnda'])) {
784
                    $OtraMoneda['ImpRetOtrMnda'] = false; // TODO
785
                }
786
                // calcular monto total
787
                if (empty($OtraMoneda['MntTotOtrMnda'])) {
788
                    $OtraMoneda['MntTotOtrMnda'] = 0;
789
                    $cols = ['MntNetoOtrMnda', 'MntExeOtrMnda', 'MntFaeCarneOtrMnda', 'MntMargComOtrMnda', 'IVAOtrMnda', 'IVANoRetOtrMnda'];
790
                    foreach ($cols as $monto) {
791
                        if (!empty($OtraMoneda[$monto])) {
792
                            $OtraMoneda['MntTotOtrMnda'] += $OtraMoneda[$monto];
793
                        }
794
                    }
795
                    // agregar total de impuesto retenido otra moneda
796
                    if (!empty($OtraMoneda['ImpRetOtrMnda'])) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
797
                        // TODO
798
                    }
799
                    // aproximar el total si es en pesos chilenos
800
                    if ($OtraMoneda['TpoMoneda']=='PESO CL') {
801
                        $OtraMoneda['MntTotOtrMnda'] = round($OtraMoneda['MntTotOtrMnda']);
802
                    }
803
                }
804
                // si el tipo de cambio es 0, se quita
805
                if ($OtraMoneda['TpoCambio']==0) {
806
                    $OtraMoneda['TpoCambio'] = false;
807
                }
808
            }
809
        }
810
    }
811
812
    /**
813
     * Método que normaliza los datos de una factura electrónica
814
     * @param datos Arreglo con los datos del documento que se desean normalizar
815
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
816
     * @version 2017-09-01
817
     */
818
    private function normalizar_33(array &$datos)
819
    {
820
        // completar con nodos por defecto
821
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
822
            'Encabezado' => [
823
                'IdDoc' => false,
824
                'Emisor' => false,
825
                'RUTMandante' => false,
826
                'Receptor' => false,
827
                'RUTSolicita' => false,
828
                'Transporte' => false,
829
                'Totales' => [
830
                    'MntNeto' => 0,
831
                    'MntExe' => false,
832
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
833
                    'IVA' => 0,
834
                    'ImptoReten' => false,
835
                    'CredEC' => false,
836
                    'MntTotal' => 0,
837
                ],
838
                'OtraMoneda' => false,
839
            ],
840
        ], $datos);
841
        // normalizar datos
842
        $this->normalizar_detalle($datos);
843
        $this->normalizar_aplicar_descuentos_recargos($datos);
844
        $this->normalizar_impuesto_retenido($datos);
845
        $this->normalizar_agregar_IVA_MntTotal($datos);
846
        $this->normalizar_transporte($datos);
847
    }
848
849
    /**
850
     * Método que normaliza los datos de una factura exenta 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 2017-02-23
854
     */
855
    private function normalizar_34(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
                    'MntExe' => false,
866
                    'MntTotal' => 0,
867
                ]
868
            ],
869
        ], $datos);
870
        // normalizar datos
871
        $this->normalizar_detalle($datos);
872
        $this->normalizar_aplicar_descuentos_recargos($datos);
873
        $this->normalizar_agregar_IVA_MntTotal($datos);
874
    }
875
876
    /**
877
     * Método que normaliza los datos de una boleta electrónica
878
     * @param datos Arreglo con los datos del documento que se desean normalizar
879
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
880
     * @version 2016-03-14
881
     */
882 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...
883
    {
884
        // completar con nodos por defecto
885
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
886
            'Encabezado' => [
887
                'IdDoc' => false,
888
                'Emisor' => [
889
                    'RUTEmisor' => false,
890
                    'RznSocEmisor' => false,
891
                    'GiroEmisor' => false,
892
                ],
893
                'Receptor' => false,
894
                'Totales' => [
895
                    'MntExe' => false,
896
                    'MntTotal' => 0,
897
                ]
898
            ],
899
        ], $datos);
900
        // normalizar datos
901
        $this->normalizar_boletas($datos);
902
        $this->normalizar_detalle($datos);
903
        $this->normalizar_aplicar_descuentos_recargos($datos);
904
        $this->normalizar_agregar_IVA_MntTotal($datos);
905
    }
906
907
    /**
908
     * Método que normaliza los datos de una boleta exenta electrónica
909
     * @param datos Arreglo con los datos del documento que se desean normalizar
910
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
911
     * @version 2016-03-14
912
     */
913 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...
914
    {
915
        // completar con nodos por defecto
916
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
917
            'Encabezado' => [
918
                'IdDoc' => false,
919
                'Emisor' => [
920
                    'RUTEmisor' => false,
921
                    'RznSocEmisor' => false,
922
                    'GiroEmisor' => false,
923
                ],
924
                'Receptor' => false,
925
                'Totales' => [
926
                    'MntExe' => 0,
927
                    'MntTotal' => 0,
928
                ]
929
            ],
930
        ], $datos);
931
        // normalizar datos
932
        $this->normalizar_boletas($datos);
933
        $this->normalizar_detalle($datos);
934
        $this->normalizar_aplicar_descuentos_recargos($datos);
935
        $this->normalizar_agregar_IVA_MntTotal($datos);
936
    }
937
938
    /**
939
     * Método que normaliza los datos de una factura de compra electrónica
940
     * @param datos Arreglo con los datos del documento que se desean normalizar
941
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
942
     * @version 2016-02-26
943
     */
944
    private function normalizar_46(array &$datos)
945
    {
946
        // completar con nodos por defecto
947
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
948
            'Encabezado' => [
949
                'IdDoc' => false,
950
                'Emisor' => false,
951
                'Receptor' => false,
952
                'RUTSolicita' => false,
953
                'Totales' => [
954
                    'MntNeto' => 0,
955
                    'MntExe' => false,
956
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
957
                    'IVA' => 0,
958
                    'ImptoReten' => false,
959
                    'IVANoRet' => false,
960
                    'MntTotal' => 0,
961
                ]
962
            ],
963
        ], $datos);
964
        // normalizar datos
965
        $this->normalizar_detalle($datos);
966
        $this->normalizar_aplicar_descuentos_recargos($datos);
967
        $this->normalizar_impuesto_retenido($datos);
968
        $this->normalizar_agregar_IVA_MntTotal($datos);
969
    }
970
971
    /**
972
     * Método que normaliza los datos de una guía de despacho electrónica
973
     * @param datos Arreglo con los datos del documento que se desean normalizar
974
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
975
     * @version 2017-09-01
976
     */
977
    private function normalizar_52(array &$datos)
978
    {
979
        // completar con nodos por defecto
980
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
981
            'Encabezado' => [
982
                'IdDoc' => false,
983
                'Emisor' => false,
984
                'Receptor' => false,
985
                'RUTSolicita' => false,
986
                'Transporte' => false,
987
                'Totales' => [
988
                    'MntNeto' => 0,
989
                    'MntExe' => false,
990
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
991
                    'IVA' => 0,
992
                    'ImptoReten' => false,
993
                    'CredEC' => false,
994
                    'MntTotal' => 0,
995
                ]
996
            ],
997
        ], $datos);
998
        // si es traslado interno se copia el emisor en el receptor sólo si el
999
        // receptor no está definido o bien si el receptor tiene RUT diferente
1000
        // al emisor
1001
        if ($datos['Encabezado']['IdDoc']['IndTraslado']==5) {
1002
            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...
1003
                $datos['Encabezado']['Receptor'] = [];
1004
                $cols = [
1005
                    'RUTEmisor'=>'RUTRecep',
1006
                    'RznSoc'=>'RznSocRecep',
1007
                    'GiroEmis'=>'GiroRecep',
1008
                    'Telefono'=>'Contacto',
1009
                    'CorreoEmisor'=>'CorreoRecep',
1010
                    'DirOrigen'=>'DirRecep',
1011
                    'CmnaOrigen'=>'CmnaRecep',
1012
                ];
1013
                foreach ($cols as $emisor => $receptor) {
1014
                    if (!empty($datos['Encabezado']['Emisor'][$emisor])) {
1015
                        $datos['Encabezado']['Receptor'][$receptor] = $datos['Encabezado']['Emisor'][$emisor];
1016
                    }
1017
                }
1018 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...
1019
                    $datos['Encabezado']['Receptor']['GiroRecep'] = mb_substr($datos['Encabezado']['Receptor']['GiroRecep'], 0, 40);
1020
                }
1021
            }
1022
        }
1023
        // normalizar datos
1024
        $this->normalizar_detalle($datos);
1025
        $this->normalizar_aplicar_descuentos_recargos($datos);
1026
        $this->normalizar_impuesto_retenido($datos);
1027
        $this->normalizar_agregar_IVA_MntTotal($datos);
1028
        $this->normalizar_transporte($datos);
1029
    }
1030
1031
    /**
1032
     * Método que normaliza los datos de una nota de débito
1033
     * @param datos Arreglo con los datos del documento que se desean normalizar
1034
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1035
     * @version 2017-02-23
1036
     */
1037 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...
1038
    {
1039
        // completar con nodos por defecto
1040
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1041
            'Encabezado' => [
1042
                'IdDoc' => false,
1043
                'Emisor' => false,
1044
                'Receptor' => false,
1045
                'RUTSolicita' => false,
1046
                'Totales' => [
1047
                    'MntNeto' => 0,
1048
                    'MntExe' => 0,
1049
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
1050
                    'IVA' => false,
1051
                    'ImptoReten' => false,
1052
                    'IVANoRet' => false,
1053
                    'CredEC' => false,
1054
                    'MntTotal' => 0,
1055
                ]
1056
            ],
1057
        ], $datos);
1058
        // normalizar datos
1059
        $this->normalizar_detalle($datos);
1060
        $this->normalizar_aplicar_descuentos_recargos($datos);
1061
        $this->normalizar_impuesto_retenido($datos);
1062
        $this->normalizar_agregar_IVA_MntTotal($datos);
1063
        if (!$datos['Encabezado']['Totales']['MntNeto']) {
1064
            $datos['Encabezado']['Totales']['MntNeto'] = 0;
1065
            $datos['Encabezado']['Totales']['TasaIVA'] = false;
1066
        }
1067
    }
1068
1069
    /**
1070
     * Método que normaliza los datos de una nota de crédito
1071
     * @param datos Arreglo con los datos del documento que se desean normalizar
1072
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1073
     * @version 2017-02-23
1074
     */
1075 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...
1076
    {
1077
        // completar con nodos por defecto
1078
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1079
            'Encabezado' => [
1080
                'IdDoc' => false,
1081
                'Emisor' => false,
1082
                'Receptor' => false,
1083
                'RUTSolicita' => false,
1084
                'Totales' => [
1085
                    'MntNeto' => 0,
1086
                    'MntExe' => 0,
1087
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
1088
                    'IVA' => false,
1089
                    'ImptoReten' => false,
1090
                    'IVANoRet' => false,
1091
                    'CredEC' => false,
1092
                    'MntTotal' => 0,
1093
                ]
1094
            ],
1095
        ], $datos);
1096
        // normalizar datos
1097
        $this->normalizar_detalle($datos);
1098
        $this->normalizar_aplicar_descuentos_recargos($datos);
1099
        $this->normalizar_impuesto_retenido($datos);
1100
        $this->normalizar_agregar_IVA_MntTotal($datos);
1101
        if (!$datos['Encabezado']['Totales']['MntNeto']) {
1102
            $datos['Encabezado']['Totales']['MntNeto'] = 0;
1103
            $datos['Encabezado']['Totales']['TasaIVA'] = false;
1104
        }
1105
    }
1106
1107
    /**
1108
     * Método que normaliza los datos de una factura electrónica de exportación
1109
     * @param datos Arreglo con los datos del documento que se desean normalizar
1110
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1111
     * @version 2016-04-05
1112
     */
1113 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...
1114
    {
1115
        // completar con nodos por defecto
1116
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1117
            'Encabezado' => [
1118
                'IdDoc' => false,
1119
                'Emisor' => false,
1120
                'Receptor' => false,
1121
                'Transporte' => [
1122
                    'Patente' => false,
1123
                    'RUTTrans' => false,
1124
                    'Chofer' => false,
1125
                    'DirDest' => false,
1126
                    'CmnaDest' => false,
1127
                    'CiudadDest' => false,
1128
                    'Aduana' => [
1129
                        'CodModVenta' => false,
1130
                        'CodClauVenta' => false,
1131
                        'TotClauVenta' => false,
1132
                        'CodViaTransp' => false,
1133
                        'NombreTransp' => false,
1134
                        'RUTCiaTransp' => false,
1135
                        'NomCiaTransp' => false,
1136
                        'IdAdicTransp' => false,
1137
                        'Booking' => false,
1138
                        'Operador' => false,
1139
                        'CodPtoEmbarque' => false,
1140
                        'IdAdicPtoEmb' => false,
1141
                        'CodPtoDesemb' => false,
1142
                        'IdAdicPtoDesemb' => false,
1143
                        'Tara' => false,
1144
                        'CodUnidMedTara' => false,
1145
                        'PesoBruto' => false,
1146
                        'CodUnidPesoBruto' => false,
1147
                        'PesoNeto' => false,
1148
                        'CodUnidPesoNeto' => false,
1149
                        'TotItems' => false,
1150
                        'TotBultos' => false,
1151
                        'TipoBultos' => false,
1152
                        'MntFlete' => false,
1153
                        'MntSeguro' => false,
1154
                        'CodPaisRecep' => false,
1155
                        'CodPaisDestin' => false,
1156
                    ],
1157
                ],
1158
                'Totales' => [
1159
                    'TpoMoneda' => null,
1160
                    'MntExe' => 0,
1161
                    'MntTotal' => 0,
1162
                ]
1163
            ],
1164
        ], $datos);
1165
        // normalizar datos
1166
        $this->normalizar_detalle($datos);
1167
        $this->normalizar_aplicar_descuentos_recargos($datos);
1168
        $this->normalizar_impuesto_retenido($datos);
1169
        $this->normalizar_agregar_IVA_MntTotal($datos);
1170
        $this->normalizar_exportacion($datos);
1171
    }
1172
1173
    /**
1174
     * Método que normaliza los datos de una nota de débito de exportación
1175
     * @param datos Arreglo con los datos del documento que se desean normalizar
1176
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1177
     * @version 2016-04-05
1178
     */
1179 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...
1180
    {
1181
        // completar con nodos por defecto
1182
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1183
            'Encabezado' => [
1184
                'IdDoc' => false,
1185
                'Emisor' => false,
1186
                'Receptor' => false,
1187
                'Transporte' => [
1188
                    'Patente' => false,
1189
                    'RUTTrans' => false,
1190
                    'Chofer' => false,
1191
                    'DirDest' => false,
1192
                    'CmnaDest' => false,
1193
                    'CiudadDest' => false,
1194
                    'Aduana' => [
1195
                        'CodModVenta' => false,
1196
                        'CodClauVenta' => false,
1197
                        'TotClauVenta' => false,
1198
                        'CodViaTransp' => false,
1199
                        'NombreTransp' => false,
1200
                        'RUTCiaTransp' => false,
1201
                        'NomCiaTransp' => false,
1202
                        'IdAdicTransp' => false,
1203
                        'Booking' => false,
1204
                        'Operador' => false,
1205
                        'CodPtoEmbarque' => false,
1206
                        'IdAdicPtoEmb' => false,
1207
                        'CodPtoDesemb' => false,
1208
                        'IdAdicPtoDesemb' => false,
1209
                        'Tara' => false,
1210
                        'CodUnidMedTara' => false,
1211
                        'PesoBruto' => false,
1212
                        'CodUnidPesoBruto' => false,
1213
                        'PesoNeto' => false,
1214
                        'CodUnidPesoNeto' => false,
1215
                        'TotItems' => false,
1216
                        'TotBultos' => false,
1217
                        'TipoBultos' => false,
1218
                        'MntFlete' => false,
1219
                        'MntSeguro' => false,
1220
                        'CodPaisRecep' => false,
1221
                        'CodPaisDestin' => false,
1222
                    ],
1223
                ],
1224
                'Totales' => [
1225
                    'TpoMoneda' => null,
1226
                    'MntExe' => 0,
1227
                    'MntTotal' => 0,
1228
                ]
1229
            ],
1230
        ], $datos);
1231
        // normalizar datos
1232
        $this->normalizar_detalle($datos);
1233
        $this->normalizar_aplicar_descuentos_recargos($datos);
1234
        $this->normalizar_impuesto_retenido($datos);
1235
        $this->normalizar_agregar_IVA_MntTotal($datos);
1236
        $this->normalizar_exportacion($datos);
1237
    }
1238
1239
    /**
1240
     * Método que normaliza los datos de una nota de crédito de exportación
1241
     * @param datos Arreglo con los datos del documento que se desean normalizar
1242
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1243
     * @version 2016-04-05
1244
     */
1245 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...
1246
    {
1247
        // completar con nodos por defecto
1248
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1249
            'Encabezado' => [
1250
                'IdDoc' => false,
1251
                'Emisor' => false,
1252
                'Receptor' => false,
1253
                'Transporte' => [
1254
                    'Patente' => false,
1255
                    'RUTTrans' => false,
1256
                    'Chofer' => false,
1257
                    'DirDest' => false,
1258
                    'CmnaDest' => false,
1259
                    'CiudadDest' => false,
1260
                    'Aduana' => [
1261
                        'CodModVenta' => false,
1262
                        'CodClauVenta' => false,
1263
                        'TotClauVenta' => false,
1264
                        'CodViaTransp' => false,
1265
                        'NombreTransp' => false,
1266
                        'RUTCiaTransp' => false,
1267
                        'NomCiaTransp' => false,
1268
                        'IdAdicTransp' => false,
1269
                        'Booking' => false,
1270
                        'Operador' => false,
1271
                        'CodPtoEmbarque' => false,
1272
                        'IdAdicPtoEmb' => false,
1273
                        'CodPtoDesemb' => false,
1274
                        'IdAdicPtoDesemb' => false,
1275
                        'Tara' => false,
1276
                        'CodUnidMedTara' => false,
1277
                        'PesoBruto' => false,
1278
                        'CodUnidPesoBruto' => false,
1279
                        'PesoNeto' => false,
1280
                        'CodUnidPesoNeto' => false,
1281
                        'TotItems' => false,
1282
                        'TotBultos' => false,
1283
                        'TipoBultos' => false,
1284
                        'MntFlete' => false,
1285
                        'MntSeguro' => false,
1286
                        'CodPaisRecep' => false,
1287
                        'CodPaisDestin' => false,
1288
                    ],
1289
                ],
1290
                'Totales' => [
1291
                    'TpoMoneda' => null,
1292
                    'MntExe' => 0,
1293
                    'MntTotal' => 0,
1294
                ]
1295
            ],
1296
        ], $datos);
1297
        // normalizar datos
1298
        $this->normalizar_detalle($datos);
1299
        $this->normalizar_aplicar_descuentos_recargos($datos);
1300
        $this->normalizar_impuesto_retenido($datos);
1301
        $this->normalizar_agregar_IVA_MntTotal($datos);
1302
        $this->normalizar_exportacion($datos);
1303
    }
1304
1305
    /**
1306
     * Método que normaliza los datos de exportacion de un documento
1307
     * @param datos Arreglo con los datos del documento que se desean normalizar
1308
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1309
     * @version 2017-10-15
1310
     */
1311
    public function normalizar_exportacion(array &$datos)
1312
    {
1313
        // agregar modalidad de venta por defecto si no existe
1314
        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...
1315
            $datos['Encabezado']['Transporte']['Aduana']['CodModVenta'] = 1;
1316
        }
1317
        // quitar campos que no son parte del documento de exportacion
1318
        $datos['Encabezado']['Receptor']['CmnaRecep'] = false;
1319
        // colocar forma de pago de exportación
1320
        if (!empty($datos['Encabezado']['IdDoc']['FmaPago'])) {
1321
            $formas = [3 => 21];
1322 View Code Duplication
            if (isset($formas[$datos['Encabezado']['IdDoc']['FmaPago']])) {
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...
1323
                $datos['Encabezado']['IdDoc']['FmaPagExp'] = $formas[$datos['Encabezado']['IdDoc']['FmaPago']];
1324
            }
1325
            $datos['Encabezado']['IdDoc']['FmaPago'] = false;
1326
        }
1327
        // si es entrega gratuita se coloca el tipo de cambio en CLP en 0 para que total sea 0
1328
        if (!empty($datos['Encabezado']['IdDoc']['FmaPagExp']) and $datos['Encabezado']['IdDoc']['FmaPagExp']==21 and !empty($datos['Encabezado']['OtraMoneda'])) {
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...
1329 View Code Duplication
            if (!isset($datos['Encabezado']['OtraMoneda'][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...
1330
                $datos['Encabezado']['OtraMoneda'] = [$datos['Encabezado']['OtraMoneda']];
1331
            }
1332
            foreach ($datos['Encabezado']['OtraMoneda'] as &$OtraMoneda) {
1333
                if ($OtraMoneda['TpoMoneda']=='PESO CL') {
1334
                    $OtraMoneda['TpoCambio'] = 0;
1335
                }
1336
            }
1337
        }
1338
    }
1339
1340
    /**
1341
     * Método que normaliza los detalles del documento
1342
     * @param datos Arreglo con los datos del documento que se desean normalizar
1343
     * @warning Revisar como se aplican descuentos y recargos, ¿debería ser un porcentaje del monto original?
1344
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1345
     * @version 2017-07-24
1346
     */
1347
    private function normalizar_detalle(array &$datos)
1348
    {
1349
        if (!isset($datos['Detalle'][0]))
1350
            $datos['Detalle'] = [$datos['Detalle']];
1351
        $item = 1;
1352
        foreach ($datos['Detalle'] as &$d) {
1353
            $d = array_merge([
1354
                'NroLinDet' => $item++,
1355
                'CdgItem' => false,
1356
                'IndExe' => false,
1357
                'Retenedor' => false,
1358
                'NmbItem' => false,
1359
                'DscItem' => false,
1360
                'QtyRef' => false,
1361
                'UnmdRef' => false,
1362
                'PrcRef' => false,
1363
                'QtyItem' => false,
1364
                'Subcantidad' => false,
1365
                'FchElabor' => false,
1366
                'FchVencim' => false,
1367
                'UnmdItem' => false,
1368
                'PrcItem' => false,
1369
                'DescuentoPct' => false,
1370
                'DescuentoMonto' => false,
1371
                'RecargoPct' => false,
1372
                'RecargoMonto' => false,
1373
                'CodImpAdic' => false,
1374
                'MontoItem' => false,
1375
            ], $d);
1376
            // corregir datos
1377
            $d['NmbItem'] = mb_substr($d['NmbItem'], 0, 80);
1378
            if (!empty($d['DscItem'])) {
1379
                $d['DscItem'] = mb_substr($d['DscItem'], 0, 1000);
1380
            }
1381
            // normalizar
1382
            if ($this->esExportacion()) {
1383
                $d['IndExe'] = 1;
1384
            }
1385
            if (is_array($d['CdgItem'])) {
1386
                $d['CdgItem'] = array_merge([
1387
                    'TpoCodigo' => false,
1388
                    'VlrCodigo' => false,
1389
                ], $d['CdgItem']);
1390
                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...
1391
                    $d['Retenedor'] = true;
1392
                }
1393
            }
1394
            if ($d['Retenedor']!==false) {
1395
                if (!is_array($d['Retenedor'])) {
1396
                    $d['Retenedor'] = ['IndAgente'=>'R'];
1397
                }
1398
                $d['Retenedor'] = array_merge([
1399
                    'IndAgente' => 'R',
1400
                    'MntBaseFaena' => false,
1401
                    'MntMargComer' => false,
1402
                    'PrcConsFinal' => false,
1403
                ], $d['Retenedor']);
1404
            }
1405
            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...
1406
                $d['CdgItem'] = [
1407
                    'TpoCodigo' => empty($d['Retenedor']['IndAgente']) ? 'INT1' : 'CPCS',
1408
                    'VlrCodigo' => $d['CdgItem'],
1409
                ];
1410
            }
1411
            if ($d['PrcItem']) {
1412
                if (!$d['QtyItem'])
1413
                    $d['QtyItem'] = 1;
1414
                if (empty($d['MontoItem'])) {
1415
                    $d['MontoItem'] = $this->round(
1416
                        $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...
1417
                        $datos['Encabezado']['Totales']['TpoMoneda']
1418
                    );
1419
                    // aplicar descuento
1420
                    if ($d['DescuentoPct']) {
1421
                        $d['DescuentoMonto'] = round($d['MontoItem'] * (int)$d['DescuentoPct']/100);
1422
                    }
1423
                    $d['MontoItem'] -= $d['DescuentoMonto'];
1424
                    // aplicar recargo
1425
                    if ($d['RecargoPct']) {
1426
                        $d['RecargoMonto'] = round($d['MontoItem'] * (int)$d['RecargoPct']/100);
1427
                    }
1428
                    $d['MontoItem'] += $d['RecargoMonto'];
1429
                    // aproximar monto del item
1430
                    $d['MontoItem'] = $this->round(
1431
                        $d['MontoItem'], $datos['Encabezado']['Totales']['TpoMoneda']
1432
                    );
1433
                }
1434
            } else if (empty($d['MontoItem'])) {
1435
                $d['MontoItem'] = 0;
1436
            }
1437
            // sumar valor del monto a MntNeto o MntExe según corresponda
1438
            if ($d['MontoItem']) {
1439
                // si no es boleta
1440
                if (!$this->esBoleta()) {
1441
                    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...
1442
                        $datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
1443 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...
1444
                        if (!empty($d['IndExe'])) {
1445
                            if ($d['IndExe']==1) {
1446
                                $datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
1447
                            }
1448
                        } else {
1449
                            $datos['Encabezado']['Totales']['MntNeto'] += $d['MontoItem'];
1450
                        }
1451
                    }
1452
                }
1453
                // si es boleta
1454 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...
1455
                    // si es exento
1456
                    if (!empty($d['IndExe'])) {
1457
                        if ($d['IndExe']==1) {
1458
                            $datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
1459
                        }
1460
                    }
1461
                    // agregar al monto total
1462
                    $datos['Encabezado']['Totales']['MntTotal'] += $d['MontoItem'];
1463
                }
1464
            }
1465
        }
1466
    }
1467
1468
    /**
1469
     * Método que aplica los descuentos y recargos generales respectivos a los
1470
     * montos que correspondan según e indicador del descuento o recargo
1471
     * @param datos Arreglo con los datos del documento que se desean normalizar
1472
     * @warning Boleta afecta con algún item exento el descuento se podría estar aplicando mal
1473
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1474
     * @version 2017-09-06
1475
     */
1476
    private function normalizar_aplicar_descuentos_recargos(array &$datos)
1477
    {
1478
        if (!empty($datos['DscRcgGlobal'])) {
1479 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...
1480
                $datos['DscRcgGlobal'] = [$datos['DscRcgGlobal']];
1481
            foreach ($datos['DscRcgGlobal'] as &$dr) {
1482
                $dr = array_merge([
1483
                    'NroLinDR' => false,
1484
                    'TpoMov' => false,
1485
                    'GlosaDR' => false,
1486
                    'TpoValor' => false,
1487
                    'ValorDR' => false,
1488
                    'ValorDROtrMnda' => false,
1489
                    'IndExeDR' => false,
1490
                ], $dr);
1491
                if ($this->esExportacion()) {
1492
                    $dr['IndExeDR'] = 1;
1493
                }
1494
                // determinar a que aplicar el descuento/recargo
1495
                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...
1496
                    $monto = $this->getTipo()==39 ? 'MntTotal' : 'MntNeto';
1497
                } else if ($dr['IndExeDR']==1) {
1498
                    $monto = 'MntExe';
1499
                } else if ($dr['IndExeDR']==2) {
1500
                    $monto = 'MontoNF';
1501
                }
1502
                // si no hay monto al que aplicar el descuento se omite
1503
                if (empty($datos['Encabezado']['Totales'][$monto])) {
1504
                    continue;
1505
                }
1506
                // calcular valor del descuento o recargo
1507
                if ($dr['TpoValor']=='$') {
1508
                    $dr['ValorDR'] = $this->round($dr['ValorDR'], $datos['Encabezado']['Totales']['TpoMoneda'], 2);
1509
                }
1510
                $valor =
1511
                    $dr['TpoValor']=='%'
1512
                    ? $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...
1513
                    : $dr['ValorDR']
1514
                ;
1515
                // aplicar descuento
1516
                if ($dr['TpoMov']=='D') {
1517
                    $datos['Encabezado']['Totales'][$monto] -= $valor;
1518
                }
1519
                // aplicar recargo
1520
                else if ($dr['TpoMov']=='R') {
1521
                    $datos['Encabezado']['Totales'][$monto] += $valor;
1522
                }
1523
                $datos['Encabezado']['Totales'][$monto] = $this->round(
1524
                    $datos['Encabezado']['Totales'][$monto],
1525
                    $datos['Encabezado']['Totales']['TpoMoneda']
1526
                );
1527
                // si el descuento global se aplica a una boleta exenta se copia el valor exento al total
1528
                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...
1529
                    $datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntExe'];
1530
                }
1531
            }
1532
        }
1533
    }
1534
1535
    /**
1536
     * Método que calcula los montos de impuestos adicionales o retenciones
1537
     * @param datos Arreglo con los datos del documento que se desean normalizar
1538
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1539
     * @version 2016-04-05
1540
     */
1541
    private function normalizar_impuesto_retenido(array &$datos)
1542
    {
1543
        // copiar montos
1544
        $montos = [];
1545
        foreach ($datos['Detalle'] as &$d) {
1546
            if (!empty($d['CodImpAdic'])) {
1547
                if (!isset($montos[$d['CodImpAdic']]))
1548
                    $montos[$d['CodImpAdic']] = 0;
1549
                $montos[$d['CodImpAdic']] += $d['MontoItem'];
1550
            }
1551
        }
1552
        // si hay montos y no hay total para impuesto retenido se arma
1553
        if (!empty($montos)) {
1554 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...
1555
                $datos['Encabezado']['Totales']['ImptoReten'] = [];
1556
            } else if (!isset($datos['Encabezado']['Totales']['ImptoReten'][0])) {
1557
                $datos['Encabezado']['Totales']['ImptoReten'] = [$datos['Encabezado']['Totales']['ImptoReten']];
1558
            }
1559
        }
1560
        // armar impuesto adicional o retención en los totales
1561
        foreach ($montos as $codigo => $neto) {
1562
            // buscar si existe el impuesto en los totales
1563
            $i = 0;
1564
            foreach ($datos['Encabezado']['Totales']['ImptoReten'] as &$ImptoReten) {
1565
                if ($ImptoReten['TipoImp']==$codigo) {
1566
                    break;
1567
                }
1568
                $i++;
1569
            }
1570
            // si no existe se crea
1571 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...
1572
                $datos['Encabezado']['Totales']['ImptoReten'][] = [
1573
                    'TipoImp' => $codigo
1574
                ];
1575
            }
1576
            // se normaliza
1577
            $datos['Encabezado']['Totales']['ImptoReten'][$i] = array_merge([
1578
                'TipoImp' => $codigo,
1579
                'TasaImp' => ImpuestosAdicionales::getTasa($codigo),
1580
                'MontoImp' => null,
1581
            ], $datos['Encabezado']['Totales']['ImptoReten'][$i]);
1582
            // si el monto no existe se asigna
1583
            if ($datos['Encabezado']['Totales']['ImptoReten'][$i]['MontoImp']===null) {
1584
                $datos['Encabezado']['Totales']['ImptoReten'][$i]['MontoImp'] = round(
1585
                    $neto * $datos['Encabezado']['Totales']['ImptoReten'][$i]['TasaImp']/100
1586
                );
1587
            }
1588
        }
1589
        // quitar los codigos que no existen en el detalle
1590
        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...
1591
            $codigos = array_keys($montos);
1592
            $n_impuestos = count($datos['Encabezado']['Totales']['ImptoReten']);
1593
            for ($i=0; $i<$n_impuestos; $i++) {
1594 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...
1595
                    unset($datos['Encabezado']['Totales']['ImptoReten'][$i]);
1596
                }
1597
            }
1598
            sort($datos['Encabezado']['Totales']['ImptoReten']);
1599
        }
1600
    }
1601
1602
    /**
1603
     * Método que calcula el monto del IVA y el monto total del documento a
1604
     * partir del monto neto y la tasa de IVA si es que existe
1605
     * @param datos Arreglo con los datos del documento que se desean normalizar
1606
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1607
     * @version 2016-04-05
1608
     */
1609
    private function normalizar_agregar_IVA_MntTotal(array &$datos)
1610
    {
1611
        // agregar IVA y monto total
1612
        if (!empty($datos['Encabezado']['Totales']['MntNeto'])) {
1613
            if ($datos['Encabezado']['IdDoc']['MntBruto']==1) {
1614
                list($datos['Encabezado']['Totales']['MntNeto'], $datos['Encabezado']['Totales']['IVA']) = $this->calcularNetoIVA(
1615
                    $datos['Encabezado']['Totales']['MntNeto'],
1616
                    $datos['Encabezado']['Totales']['TasaIVA']
1617
                );
1618
            } else {
1619
                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...
1620
                    $datos['Encabezado']['Totales']['IVA'] = round(
1621
                        $datos['Encabezado']['Totales']['MntNeto']*($datos['Encabezado']['Totales']['TasaIVA']/100)
1622
                    );
1623
                }
1624
            }
1625
            if (empty($datos['Encabezado']['Totales']['MntTotal'])) {
1626
                $datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntNeto'];
1627
                if (!empty($datos['Encabezado']['Totales']['IVA']))
1628
                    $datos['Encabezado']['Totales']['MntTotal'] += $datos['Encabezado']['Totales']['IVA'];
1629
                if (!empty($datos['Encabezado']['Totales']['MntExe']))
1630
                    $datos['Encabezado']['Totales']['MntTotal'] += $datos['Encabezado']['Totales']['MntExe'];
1631
            }
1632 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...
1633
            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...
1634
                $datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntExe'];
1635
            }
1636
        }
1637
        // si hay impuesto retenido o adicional se contabiliza en el total
1638
        if (!empty($datos['Encabezado']['Totales']['ImptoReten'])) {
1639
            foreach ($datos['Encabezado']['Totales']['ImptoReten'] as &$ImptoReten) {
1640
                // si es retención se resta al total y se traspasaa IVA no retenido
1641
                // en caso que corresponda
1642
                if (ImpuestosAdicionales::getTipo($ImptoReten['TipoImp'])=='R') {
1643
                    $datos['Encabezado']['Totales']['MntTotal'] -= $ImptoReten['MontoImp'];
1644
                    if ($ImptoReten['MontoImp']!=$datos['Encabezado']['Totales']['IVA']) {
1645
                        $datos['Encabezado']['Totales']['IVANoRet'] = $datos['Encabezado']['Totales']['IVA'] - $ImptoReten['MontoImp'];
1646
                    }
1647
                }
1648
                // si es adicional se suma al total
1649
                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...
1650
                    $datos['Encabezado']['Totales']['MntTotal'] += $ImptoReten['MontoImp'];
1651
                }
1652
            }
1653
        }
1654
        // si hay impuesto de crédito a constructoras del 65% se descuenta del total
1655
        if (!empty($datos['Encabezado']['Totales']['CredEC'])) {
1656
            if ($datos['Encabezado']['Totales']['CredEC']===true)
1657
                $datos['Encabezado']['Totales']['CredEC'] = round($datos['Encabezado']['Totales']['IVA'] * 0.65); // TODO: mover a constante o método
1658
            $datos['Encabezado']['Totales']['MntTotal'] -= $datos['Encabezado']['Totales']['CredEC'];
1659
        }
1660
    }
1661
1662
    /**
1663
     * Método que normaliza los datos de transporte
1664
     * @param datos Arreglo con los datos del documento que se desean normalizar
1665
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1666
     * @version 2017-09-01
1667
     */
1668
    private function normalizar_transporte(array &$datos)
1669
    {
1670
        if (!empty($datos['Encabezado']['Transporte'])) {
1671
            $datos['Encabezado']['Transporte'] = array_merge([
1672
                'Patente' => false,
1673
                'RUTTrans' => false,
1674
                'Chofer' => false,
1675
                'DirDest' => false,
1676
                'CmnaDest' => false,
1677
                'CiudadDest' => false,
1678
                'Aduana' => false,
1679
            ], $datos['Encabezado']['Transporte']);
1680
        }
1681
    }
1682
1683
    /**
1684
     * Método que normaliza las boletas electrónicas, dte 39 y 41
1685
     * @param datos Arreglo con los datos del documento que se desean normalizar
1686
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1687
     * @version 2017-10-04
1688
     */
1689
    private function normalizar_boletas(array &$datos)
1690
    {
1691
        // cambiar tags de DTE a boleta si se pasaron
1692 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...
1693
            $datos['Encabezado']['Emisor']['RznSocEmisor'] = $datos['Encabezado']['Emisor']['RznSoc'];
1694
            $datos['Encabezado']['Emisor']['RznSoc'] = false;
1695
        }
1696 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...
1697
            $datos['Encabezado']['Emisor']['GiroEmisor'] = $datos['Encabezado']['Emisor']['GiroEmis'];
1698
            $datos['Encabezado']['Emisor']['GiroEmis'] = false;
1699
        }
1700
        $datos['Encabezado']['Emisor']['Acteco'] = false;
1701
        $datos['Encabezado']['Emisor']['Telefono'] = false;
1702
        $datos['Encabezado']['Emisor']['CorreoEmisor'] = false;
1703
        $datos['Encabezado']['Emisor']['CdgVendedor'] = false;
1704
        $datos['Encabezado']['Receptor']['GiroRecep'] = false;
1705
        if (!empty($datos['Encabezado']['Receptor']['CorreoRecep'])) {
1706
            $datos['Referencia'][] = [
1707
                'NroLinRef' => !empty($datos['Referencia']) ? (count($datos['Referencia'])+1) : 1,
1708
                'RazonRef' => mb_substr('Email receptor: '.$datos['Encabezado']['Receptor']['CorreoRecep'], 0, 90),
1709
            ];
1710
        }
1711
        $datos['Encabezado']['Receptor']['CorreoRecep'] = false;
1712
        // quitar otros tags que no son parte de las boletas
1713
        $datos['Encabezado']['IdDoc']['FmaPago'] = false;
1714
        $datos['Encabezado']['IdDoc']['FchCancel'] = false;
1715
        $datos['Encabezado']['IdDoc']['TermPagoGlosa'] = false;
1716
        $datos['Encabezado']['RUTSolicita'] = false;
1717
        // si es boleta no nominativa se deja sólo el RUT en el campo del receptor
1718
        if ($datos['Encabezado']['Receptor']['RUTRecep']=='66666666-6') {
1719
            $datos['Encabezado']['Receptor'] = ['RUTRecep'=>'66666666-6'];
1720
        }
1721
        // ajustar las referencias si existen
1722
        if (!empty($datos['Referencia'])) {
1723 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...
1724
                $datos['Referencia'] = [$datos['Referencia']];
1725
            }
1726
            foreach ($datos['Referencia'] as &$r) {
1727
                foreach (['TpoDocRef', 'FolioRef', 'FchRef'] as $c) {
1728
                    if (isset($r[$c])) {
1729
                        unset($r[$c]);
1730
                    }
1731
                }
1732
            }
1733
        }
1734
    }
1735
1736
    /**
1737
     * Método que redondea valores. Si los montos son en pesos chilenos se
1738
     * redondea, si no se mantienen todos los decimales
1739
     * @param valor Valor que se desea redondear
1740
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1741
     * @version 2016-04-05
1742
     */
1743
    private function round($valor, $moneda = false, $decimal = 4)
1744
    {
1745
        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...
1746
    }
1747
1748
    /**
1749
     * Método que determina el estado de validación sobre el DTE, se verifica:
1750
     *  - Firma del DTE
1751
     *  - RUT del emisor (si se pasó uno para comparar)
1752
     *  - RUT del receptor (si se pasó uno para comparar)
1753
     * @return Código del estado de la validación
1754
     * @warning No se está validando la firma
1755
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1756
     * @version 2015-09-08
1757
     */
1758
    public function getEstadoValidacion(array $datos = null)
1759
    {
1760
        /*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...
1761
            return 1;*/
1762
        if (is_array($datos)) {
1763
            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...
1764
                return 2;
1765
            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...
1766
                return 3;
1767
        }
1768
        return 0;
1769
    }
1770
1771
    /**
1772
     * Método que indica si la firma del DTE es o no válida
1773
     * @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...
1774
     * @warning No se está verificando el valor del DigestValue del documento (sólo la firma de ese DigestValue)
1775
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1776
     * @version 2015-09-08
1777
     */
1778
    public function checkFirma()
1779
    {
1780
        if (!$this->xml)
1781
            return null;
1782
        // obtener firma
1783
        $Signature = $this->xml->documentElement->getElementsByTagName('Signature')->item(0);
1784
        // preparar documento a validar
1785
        $D = $this->xml->documentElement->getElementsByTagName('Documento')->item(0);
1786
        $Documento = new \sasco\LibreDTE\XML();
1787
        $Documento->loadXML($D->C14N());
1788
        $Documento->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
1789
        $Documento->documentElement->removeAttributeNS('http://www.sii.cl/SiiDte', '');
1790
        $SignedInfo = new \sasco\LibreDTE\XML();
1791
        $SignedInfo->loadXML($Signature->getElementsByTagName('SignedInfo')->item(0)->C14N());
1792
        $SignedInfo->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
1793
        $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...
1794
        $SignatureValue = $Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue;
1795
        $X509Certificate = $Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue;
1796
        $X509Certificate = '-----BEGIN CERTIFICATE-----'."\n".wordwrap(trim($X509Certificate), 64, "\n", true)."\n".'-----END CERTIFICATE----- ';
1797
        $valid = openssl_verify($SignedInfo->C14N(), base64_decode($SignatureValue), $X509Certificate) === 1 ? true : false;
1798
        return $valid;
1799
        //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...
1800
    }
1801
1802
    /**
1803
     * Método que indica si el documento es o no cedible
1804
     * @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...
1805
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1806
     * @version 2015-09-10
1807
     */
1808
    public function esCedible()
1809
    {
1810
        return !in_array($this->getTipo(), $this->noCedibles);
1811
    }
1812
1813
    /**
1814
     * Método que indica si el documento es o no una boleta electrónica
1815
     * @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...
1816
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1817
     * @version 2015-12-11
1818
     */
1819
    public function esBoleta()
1820
    {
1821
        return in_array($this->getTipo(), [39, 41]);
1822
    }
1823
1824
    /**
1825
     * Método que indica si el documento es o no una exportación
1826
     * @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...
1827
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1828
     * @version 2016-04-05
1829
     */
1830
    public function esExportacion()
1831
    {
1832
        return in_array($this->getTipo(), $this->tipos['Exportaciones']);
1833
    }
1834
1835
    /**
1836
     * Método que valida el schema del DTE
1837
     * @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...
1838
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1839
     * @version 2015-12-15
1840
     */
1841
    public function schemaValidate()
1842
    {
1843
        return true;
1844
    }
1845
1846
    /**
1847
     * Método que valida los datos del DTE
1848
     * @return =true si no hay errores de validación, =false si se encontraron errores al validar
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...
1849
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1850
     * @version 2017-02-06
1851
     */
1852
    public function verificarDatos()
1853
    {
1854
        if (class_exists('\sasco\LibreDTE\Sii\VerificadorDatos')) {
1855
            if (!\sasco\LibreDTE\Sii\VerificadorDatos::Dte($this->getDatos())) {
1856
                return false;
1857
            }
1858
        }
1859
        return true;
1860
    }
1861
1862
    /**
1863
     * Método que obtiene el estado del DTE
1864
     * @param Firma objeto que representa la Firma Electrónca
1865
     * @return Arreglo con el estado del DTE
1866
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1867
     * @version 2015-10-24
1868
     */
1869
    public function getEstado(\sasco\LibreDTE\FirmaElectronica $Firma)
1870
    {
1871
        // solicitar token
1872
        $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...
1873
        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...
1874
            return false;
1875
        // consultar estado dte
1876
        $run = $Firma->getID();
1877
        if ($run===false)
1878
            return false;
1879
        list($RutConsultante, $DvConsultante) = explode('-', $run);
1880
        list($RutCompania, $DvCompania) = explode('-', $this->getEmisor());
1881
        list($RutReceptor, $DvReceptor) = explode('-', $this->getReceptor());
1882
        list($Y, $m, $d) = explode('-', $this->getFechaEmision());
1883
        $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...
1884
            'RutConsultante'    => $RutConsultante,
1885
            'DvConsultante'     => $DvConsultante,
1886
            'RutCompania'       => $RutCompania,
1887
            'DvCompania'        => $DvCompania,
1888
            'RutReceptor'       => $RutReceptor,
1889
            'DvReceptor'        => $DvReceptor,
1890
            'TipoDte'           => $this->getTipo(),
1891
            'FolioDte'          => $this->getFolio(),
1892
            'FechaEmisionDte'   => $d.$m.$Y,
1893
            'MontoDte'          => $this->getMontoTotal(),
1894
            'token'             => $token,
1895
        ]);
1896
        // si el estado se pudo recuperar se muestra
1897
        if ($xml===false)
1898
            return false;
1899
        // entregar estado
1900
        return (array)$xml->xpath('/SII:RESPUESTA/SII:RESP_HDR')[0];
1901
    }
1902
1903
    /**
1904
     * Método que obtiene el estado avanzado del DTE
1905
     * @param Firma objeto que representa la Firma Electrónca
1906
     * @return Arreglo con el estado del DTE
1907
     * @todo Corregir warning y también definir que se retornará (sobre todo en caso de error)
1908
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1909
     * @version 2016-08-05
1910
     */
1911
    public function getEstadoAvanzado(\sasco\LibreDTE\FirmaElectronica $Firma)
1912
    {
1913
        // solicitar token
1914
        $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...
1915
        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...
1916
            return false;
1917
        // consultar estado dte
1918
        list($RutEmpresa, $DvEmpresa) = explode('-', $this->getEmisor());
1919
        list($RutReceptor, $DvReceptor) = explode('-', $this->getReceptor());
1920
        list($Y, $m, $d) = explode('-', $this->getFechaEmision());
1921
        $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...
1922
            'RutEmpresa'       => $RutEmpresa,
1923
            'DvEmpresa'        => $DvEmpresa,
1924
            'RutReceptor'       => $RutReceptor,
1925
            'DvReceptor'        => $DvReceptor,
1926
            'TipoDte'           => $this->getTipo(),
1927
            'FolioDte'          => $this->getFolio(),
1928
            'FechaEmisionDte'   => $d.'-'.$m.'-'.$Y,
1929
            'MontoDte'          => $this->getMontoTotal(),
1930
            'FirmaDte'          => str_replace("\n", '', $this->getFirma()['SignatureValue']),
1931
            'token'             => $token,
1932
        ]);
1933
        // si el estado se pudo recuperar se muestra
1934
        if ($xml===false)
1935
            return false;
1936
        // entregar estado
1937
        return (array)$xml->xpath('/SII:RESPUESTA/SII:RESP_BODY')[0];
1938
    }
1939
1940
    /**
1941
     * Método que entrega la última acción registrada para el DTE en el registro de compra y venta
1942
     * @return Arreglo con los datos de la última acción
1943
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1944
     * @version 2017-08-29
1945
     */
1946
    public function getUltimaAccionRCV(\sasco\LibreDTE\FirmaElectronica $Firma)
1947
    {
1948
        list($emisor_rut, $emisor_dv) = explode('-', $this->getEmisor());
1949
        $RCV = new \sasco\LibreDTE\Sii\RegistroCompraVenta($Firma);
1950
        try {
1951
            $eventos = $RCV->listarEventosHistDoc($emisor_rut, $emisor_dv, $this->getTipo(), $this->getFolio());
1952
            return $eventos ? $eventos[count($eventos)-1] : null;
1953
        } catch (\Exception $e) {
1954
            return null;
1955
        }
1956
    }
1957
1958
}
1959