Completed
Push — master ( 6bc34b...81fd90 )
by Esteban De La Fuente
01:54
created

Dte::getReceptor()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Importance

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