Completed
Push — master ( c4324d...6e3f9c )
by Esteban De La Fuente
01:44
created

Dte::getID()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
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;
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::getJSON 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...
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
        if (!$RSR) {
443
            $RSR = $RR;
444
        }
445
        $TED = new \sasco\LibreDTE\XML();
446
        $TED->generate([
447
            'TED' => [
448
                '@attributes' => [
449
                    'version' => '1.0',
450
                ],
451
                'DD' => [
452
                    '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...
453
                    '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...
454
                    'F' => $folio,
455
                    '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...
456
                    '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...
457
                    'RSR' => $RSR,
458
                    '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...
459
                    '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...
460
                    'CAF' => $Folios->getCaf(),
461
                    'TSTED' => $this->timestamp,
462
                ],
463
                'FRMT' => [
464
                    '@attributes' => [
465
                        'algoritmo' => 'SHA1withRSA'
466
                    ],
467
                ],
468
            ]
469
        ]);
470
        $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...
471
        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...
472
            \sasco\LibreDTE\Log::write(
473
                \sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE,
474
                \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...
475
            );
476
            return false;
477
        }
478
        $TED->getElementsByTagName('FRMT')->item(0)->nodeValue = base64_encode($timbre);
479
        $xml = str_replace('<TED/>', trim(str_replace('<?xml version="1.0" encoding="ISO-8859-1"?>', '', $TED->saveXML())), $this->saveXML());
480 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...
481
            \sasco\LibreDTE\Log::write(
482
                \sasco\LibreDTE\Estado::DTE_ERROR_TIMBRE,
483
                \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...
484
            );
485
            return false;
486
        }
487
        return true;
488
    }
489
490
    /**
491
     * Método que realiza la firma del DTE
492
     * @param Firma objeto que representa la Firma Electrónca
493
     * @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...
494
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
495
     * @version 2017-10-22
496
     */
497
    public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
498
    {
499
        $parent = $this->xml->getElementsByTagName($this->tipo_general)->item(0);
500
        $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...
501
        $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...
502 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...
503
            \sasco\LibreDTE\Log::write(
504
                \sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
505
                \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...
506
            );
507
            return false;
508
        }
509
        $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 501 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...
510
        return true;
511
    }
512
513
    /**
514
     * Método que entrega el DTE en XML
515
     * @return XML con el DTE (podría: con o sin timbre y con o sin firma)
516
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
517
     * @version 2015-08-20
518
     */
519
    public function saveXML()
520
    {
521
        return $this->xml->saveXML();
522
    }
523
524
    /**
525
     * Método que genera un arreglo con el resumen del documento. Este resumen
526
     * puede servir, por ejemplo, para generar los detalles de los IECV
527
     * @return Arreglo con el resumen del DTE
528
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
529
     * @version 2016-07-15
530
     */
531
    public function getResumen()
532
    {
533
        $this->getDatos();
534
        // generar resumen
535
        $resumen =  [
536
            'TpoDoc' => (int)$this->datos['Encabezado']['IdDoc']['TipoDTE'],
537
            'NroDoc' => (int)$this->datos['Encabezado']['IdDoc']['Folio'],
538
            'TasaImp' => 0,
539
            'FchDoc' => $this->datos['Encabezado']['IdDoc']['FchEmis'],
540
            'CdgSIISucur' => !empty($this->datos['Encabezado']['Emisor']['CdgSIISucur']) ? $this->datos['Encabezado']['Emisor']['CdgSIISucur'] : false,
541
            'RUTDoc' => $this->datos['Encabezado']['Receptor']['RUTRecep'],
542
            'RznSoc' => isset($this->datos['Encabezado']['Receptor']['RznSocRecep']) ? $this->datos['Encabezado']['Receptor']['RznSocRecep'] : false,
543
            'MntExe' => false,
544
            'MntNeto' => false,
545
            'MntIVA' => 0,
546
            'MntTotal' => 0,
547
        ];
548
        // obtener montos si es que existen en el documento
549
        $montos = ['TasaImp'=>'TasaIVA', 'MntExe'=>'MntExe', 'MntNeto'=>'MntNeto', 'MntIVA'=>'IVA', 'MntTotal'=>'MntTotal'];
550
        foreach ($montos as $dest => $orig) {
551
            if (!empty($this->datos['Encabezado']['Totales'][$orig])) {
552
                $resumen[$dest] = !$this->esExportacion() ? round($this->datos['Encabezado']['Totales'][$orig]) : $this->datos['Encabezado']['Totales'][$orig];
553
            }
554
        }
555
        // si es una boleta se calculan los datos para el resumen
556
        if ($this->esBoleta()) {
557
            if (!$resumen['TasaImp']) {
558
                $resumen['TasaImp'] = \sasco\LibreDTE\Sii::getIVA();
559
            }
560
            $resumen['MntExe'] = (int)$resumen['MntExe'];
561
            if (!$resumen['MntNeto']) {
562
                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...
563
            }
564
        }
565
        // entregar resumen
566
        return $resumen;
567
    }
568
569
    /**
570
     * Método que permite obtener el monto neto y el IVA de ese neto a partir de
571
     * un monto total
572
     * @param total neto + iva
573
     * @param tasa Tasa del IVA
574
     * @return Arreglo con el neto y el iva
575
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
576
     * @version 2016-04-05
577
     */
578
    private function calcularNetoIVA($total, $tasa = null)
579
    {
580
        if ($tasa === 0 or $tasa === false) {
581
            return [0, 0];
582
        }
583
        if ($tasa === null) {
584
            $tasa = \sasco\LibreDTE\Sii::getIVA();
585
        }
586
        // WARNING: el IVA obtenido puede no ser el NETO*(TASA/100)
587
        // se calcula el monto neto y luego se obtiene el IVA haciendo la resta
588
        // entre el total y el neto, ya que hay casos de borde como:
589
        //  - BRUTO:   680 => NETO:   571 e IVA:   108 => TOTAL:   679
590
        //  - BRUTO: 86710 => NETO: 72866 e IVA: 13845 => TOTAL: 86711
591
        $neto = round($total / (1+($tasa/100)));
592
        $iva = $total - $neto;
593
        return [$neto, $iva];
594
    }
595
596
    /**
597
     * Método que normaliza los datos de un documento tributario electrónico
598
     * @param datos Arreglo con los datos del documento que se desean normalizar
599
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
600
     * @version 2018-06-25
601
     */
602
    private function normalizar(array &$datos)
603
    {
604
        // completar con nodos por defecto
605
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
606
            'Encabezado' => [
607
                'IdDoc' => [
608
                    'TipoDTE' => false,
609
                    'Folio' => false,
610
                    'FchEmis' => date('Y-m-d'),
611
                    'IndNoRebaja' => false,
612
                    'TipoDespacho' => false,
613
                    'IndTraslado' => false,
614
                    'TpoImpresion' => false,
615
                    'IndServicio' => $this->esBoleta() ? 3 : false,
616
                    'MntBruto' => false,
617
                    'TpoTranCompra' => false,
618
                    'TpoTranVenta' => false,
619
                    'FmaPago' => false,
620
                    'FmaPagExp' => false,
621
                    'MntCancel' => false,
622
                    'SaldoInsol' => false,
623
                    'FchCancel' => false,
624
                    'MntPagos' => false,
625
                    'PeriodoDesde' => false,
626
                    'PeriodoHasta' => false,
627
                    'MedioPago' => false,
628
                    'TpoCtaPago' => false,
629
                    'NumCtaPago' => false,
630
                    'BcoPago' => false,
631
                    'TermPagoCdg' => false,
632
                    'TermPagoGlosa' => false,
633
                    'TermPagoDias' => false,
634
                    'FchVenc' => false,
635
                ],
636
                'Emisor' => [
637
                    'RUTEmisor' => false,
638
                    'RznSoc' => false,
639
                    'GiroEmis' => false,
640
                    'Telefono' => false,
641
                    'CorreoEmisor' => false,
642
                    'Acteco' => false,
643
                    'Sucursal' => false,
644
                    'CdgSIISucur' => false,
645
                    'DirOrigen' => false,
646
                    'CmnaOrigen' => false,
647
                    'CiudadOrigen' => false,
648
                    'CdgVendedor' => false,
649
                ],
650
                'Receptor' => [
651
                    'RUTRecep' => false,
652
                    'CdgIntRecep' => false,
653
                    'RznSocRecep' => false,
654
                    'Extranjero' => false,
655
                    'GiroRecep' => false,
656
                    'Contacto' => false,
657
                    'CorreoRecep' => false,
658
                    'DirRecep' => false,
659
                    'CmnaRecep' => false,
660
                    'CiudadRecep' => false,
661
                    'DirPostal' => false,
662
                    'CmnaPostal' => false,
663
                    'CiudadPostal' => false,
664
                ],
665
                'Totales' => [
666
                    'TpoMoneda' => false,
667
                ],
668
            ],
669
            'Detalle' => false,
670
            'SubTotInfo' => false,
671
            'DscRcgGlobal' => false,
672
            'Referencia' => false,
673
            'Comisiones' => false,
674
        ], $datos);
675
        // corregir algunos datos que podrían venir malos para no caer por schema
676
        $datos['Encabezado']['Emisor']['RUTEmisor'] = strtoupper(trim(str_replace('.', '', $datos['Encabezado']['Emisor']['RUTEmisor'])));
677
        $datos['Encabezado']['Receptor']['RUTRecep'] = strtoupper(trim(str_replace('.', '', $datos['Encabezado']['Receptor']['RUTRecep'])));
678
        $datos['Encabezado']['Receptor']['RznSocRecep'] = mb_substr($datos['Encabezado']['Receptor']['RznSocRecep'], 0, 100);
679 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...
680
            $datos['Encabezado']['Receptor']['GiroRecep'] = mb_substr($datos['Encabezado']['Receptor']['GiroRecep'], 0, 40);
681
        }
682 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...
683
            $datos['Encabezado']['Receptor']['Contacto'] = mb_substr($datos['Encabezado']['Receptor']['Contacto'], 0, 80);
684
        }
685 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...
686
            $datos['Encabezado']['Receptor']['CorreoRecep'] = mb_substr($datos['Encabezado']['Receptor']['CorreoRecep'], 0, 80);
687
        }
688 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...
689
            $datos['Encabezado']['Receptor']['DirRecep'] = mb_substr($datos['Encabezado']['Receptor']['DirRecep'], 0, 70);
690
        }
691 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...
692
            $datos['Encabezado']['Receptor']['CmnaRecep'] = mb_substr($datos['Encabezado']['Receptor']['CmnaRecep'], 0, 20);
693
        }
694
        if (!empty($datos['Encabezado']['Emisor']['Acteco'])) {
695
            if (strlen((string)$datos['Encabezado']['Emisor']['Acteco'])==5) {
696
                $datos['Encabezado']['Emisor']['Acteco'] = '0'.$datos['Encabezado']['Emisor']['Acteco'];
697
            }
698
        }
699
        // si existe descuento o recargo global se normalizan
700
        if (!empty($datos['DscRcgGlobal'])) {
701 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...
702
                $datos['DscRcgGlobal'] = [$datos['DscRcgGlobal']];
703
            $NroLinDR = 1;
704
            foreach ($datos['DscRcgGlobal'] as &$dr) {
705
                $dr = array_merge([
706
                    'NroLinDR' => $NroLinDR++,
707
                ], $dr);
708
            }
709
        }
710
        // si existe una o más referencias se normalizan
711
        if (!empty($datos['Referencia'])) {
712 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...
713
                $datos['Referencia'] = [$datos['Referencia']];
714
            }
715
            $NroLinRef = 1;
716
            foreach ($datos['Referencia'] as &$r) {
717
                $r = array_merge([
718
                    'NroLinRef' => $NroLinRef++,
719
                    'TpoDocRef' => false,
720
                    'IndGlobal' => false,
721
                    'FolioRef' => false,
722
                    'RUTOtr' => false,
723
                    'FchRef' => date('Y-m-d'),
724
                    'CodRef' => false,
725
                    'RazonRef' => false,
726
                ], $r);
727
            }
728
        }
729
        // verificar que exista TpoTranVenta
730
        if (!in_array($datos['Encabezado']['IdDoc']['TipoDTE'], [39, 41, 110, 111, 112]) and empty($datos['Encabezado']['IdDoc']['TpoTranVenta'])) {
731
            $datos['Encabezado']['IdDoc']['TpoTranVenta'] = 1; // ventas del giro
732
        }
733
    }
734
735
    /**
736
     * Método que realiza la normalización final de los datos de un documento
737
     * tributario electrónico. Esto se aplica todos los documentos una vez que
738
     * ya se aplicaron las normalizaciones por tipo
739
     * @param datos Arreglo con los datos del documento que se desean normalizar
740
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
741
     * @version 2017-09-23
742
     */
743
    private function normalizar_final(array &$datos)
744
    {
745
        // normalizar montos de pagos programados
746
        if (is_array($datos['Encabezado']['IdDoc']['MntPagos'])) {
747
            $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...
748
            if (!isset($datos['Encabezado']['IdDoc']['MntPagos'][0])) {
749
                $datos['Encabezado']['IdDoc']['MntPagos'] = [$datos['Encabezado']['IdDoc']['MntPagos']];
750
            }
751
            foreach ($datos['Encabezado']['IdDoc']['MntPagos'] as &$MntPagos) {
752
                $MntPagos = array_merge([
753
                    'FchPago' => null,
754
                    'MntPago' => null,
755
                    'GlosaPagos' => false,
756
                ], $MntPagos);
757
                if ($MntPagos['MntPago']===null) {
758
                    $MntPagos['MntPago'] = $datos['Encabezado']['Totales']['MntTotal'];
759
                }
760
            }
761
        }
762
        // si existe OtraMoneda se verifican los tipos de cambio y totales
763
        if (!empty($datos['Encabezado']['OtraMoneda'])) {
764 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...
765
                $datos['Encabezado']['OtraMoneda'] = [$datos['Encabezado']['OtraMoneda']];
766
            }
767
            foreach ($datos['Encabezado']['OtraMoneda'] as &$OtraMoneda) {
768
                // colocar campos por defecto
769
                $OtraMoneda = array_merge([
770
                    'TpoMoneda' => false,
771
                    'TpoCambio' => false,
772
                    'MntNetoOtrMnda' => false,
773
                    'MntExeOtrMnda' => false,
774
                    'MntFaeCarneOtrMnda' => false,
775
                    'MntMargComOtrMnda' => false,
776
                    'IVAOtrMnda' => false,
777
                    'ImpRetOtrMnda' => false,
778
                    'IVANoRetOtrMnda' => false,
779
                    'MntTotOtrMnda' => false,
780
                ], $OtraMoneda);
781
                // si no hay tipo de cambio no seguir
782
                if (!isset($OtraMoneda['TpoCambio'])) {
783
                    continue;
784
                }
785
                // buscar si los valores están asignados, si no lo están asignar
786
                // usando el tipo de cambio que existe para la moneda
787
                foreach (['MntNeto', 'MntExe', 'IVA', 'IVANoRet'] as $monto) {
788
                    if (empty($OtraMoneda[$monto.'OtrMnda']) and !empty($datos['Encabezado']['Totales'][$monto])) {
789
                        $OtraMoneda[$monto.'OtrMnda'] = round($datos['Encabezado']['Totales'][$monto] * $OtraMoneda['TpoCambio'], 4);
790
                    }
791
                }
792
                // calcular MntFaeCarneOtrMnda, MntMargComOtrMnda, ImpRetOtrMnda
793
                if (empty($OtraMoneda['MntFaeCarneOtrMnda'])) {
794
                    $OtraMoneda['MntFaeCarneOtrMnda'] = false; // TODO
795
                }
796
                if (empty($OtraMoneda['MntMargComOtrMnda'])) {
797
                    $OtraMoneda['MntMargComOtrMnda'] = false; // TODO
798
                }
799
                if (empty($OtraMoneda['ImpRetOtrMnda'])) {
800
                    $OtraMoneda['ImpRetOtrMnda'] = false; // TODO
801
                }
802
                // calcular monto total
803
                if (empty($OtraMoneda['MntTotOtrMnda'])) {
804
                    $OtraMoneda['MntTotOtrMnda'] = 0;
805
                    $cols = ['MntNetoOtrMnda', 'MntExeOtrMnda', 'MntFaeCarneOtrMnda', 'MntMargComOtrMnda', 'IVAOtrMnda', 'IVANoRetOtrMnda'];
806
                    foreach ($cols as $monto) {
807
                        if (!empty($OtraMoneda[$monto])) {
808
                            $OtraMoneda['MntTotOtrMnda'] += $OtraMoneda[$monto];
809
                        }
810
                    }
811
                    // agregar total de impuesto retenido otra moneda
812
                    if (!empty($OtraMoneda['ImpRetOtrMnda'])) {
813
                        // TODO
814
                    }
815
                    // aproximar el total si es en pesos chilenos
816
                    if ($OtraMoneda['TpoMoneda']=='PESO CL') {
817
                        $OtraMoneda['MntTotOtrMnda'] = round($OtraMoneda['MntTotOtrMnda']);
818
                    }
819
                }
820
                // si el tipo de cambio es 0, se quita
821
                if ($OtraMoneda['TpoCambio']==0) {
822
                    $OtraMoneda['TpoCambio'] = false;
823
                }
824
            }
825
        }
826
    }
827
828
    /**
829
     * Método que normaliza los datos de una factura electrónica
830
     * @param datos Arreglo con los datos del documento que se desean normalizar
831
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
832
     * @version 2017-09-01
833
     */
834
    private function normalizar_33(array &$datos)
835
    {
836
        // completar con nodos por defecto
837
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
838
            'Encabezado' => [
839
                'IdDoc' => false,
840
                'Emisor' => false,
841
                'RUTMandante' => false,
842
                'Receptor' => false,
843
                'RUTSolicita' => false,
844
                'Transporte' => false,
845
                'Totales' => [
846
                    'MntNeto' => 0,
847
                    'MntExe' => false,
848
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
849
                    'IVA' => 0,
850
                    'ImptoReten' => false,
851
                    'CredEC' => false,
852
                    'MntTotal' => 0,
853
                ],
854
                'OtraMoneda' => false,
855
            ],
856
        ], $datos);
857
        // normalizar datos
858
        $this->normalizar_detalle($datos);
859
        $this->normalizar_aplicar_descuentos_recargos($datos);
860
        $this->normalizar_impuesto_retenido($datos);
861
        $this->normalizar_agregar_IVA_MntTotal($datos);
862
        $this->normalizar_transporte($datos);
863
    }
864
865
    /**
866
     * Método que normaliza los datos de una factura exenta electrónica
867
     * @param datos Arreglo con los datos del documento que se desean normalizar
868
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
869
     * @version 2017-02-23
870
     */
871
    private function normalizar_34(array &$datos)
872
    {
873
        // completar con nodos por defecto
874
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
875
            'Encabezado' => [
876
                'IdDoc' => false,
877
                'Emisor' => false,
878
                'Receptor' => false,
879
                'RUTSolicita' => false,
880
                'Totales' => [
881
                    'MntExe' => false,
882
                    'MntTotal' => 0,
883
                ]
884
            ],
885
        ], $datos);
886
        // normalizar datos
887
        $this->normalizar_detalle($datos);
888
        $this->normalizar_aplicar_descuentos_recargos($datos);
889
        $this->normalizar_agregar_IVA_MntTotal($datos);
890
    }
891
892
    /**
893
     * Método que normaliza los datos de una boleta electrónica
894
     * @param datos Arreglo con los datos del documento que se desean normalizar
895
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
896
     * @version 2020-10-12
897
     */
898
    private function normalizar_39(array &$datos)
899
    {
900
        // completar con nodos por defecto
901
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
902
            'Encabezado' => [
903
                'IdDoc' => false,
904
                'Emisor' => [
905
                    'RUTEmisor' => false,
906
                    'RznSocEmisor' => false,
907
                    'GiroEmisor' => false,
908
                ],
909
                'Receptor' => false,
910
                'Totales' => [
911
                    'MntNeto' => false,
912
                    'MntExe' => false,
913
                    'IVA' => false,
914
                    'MntTotal' => 0,
915
                ]
916
            ],
917
        ], $datos);
918
        // normalizar datos
919
        $this->normalizar_boletas($datos);
920
        $this->normalizar_detalle($datos);
921
        $this->normalizar_aplicar_descuentos_recargos($datos);
922
        $this->normalizar_agregar_IVA_MntTotal($datos);
923
    }
924
925
    /**
926
     * Método que normaliza los datos de una boleta exenta electrónica
927
     * @param datos Arreglo con los datos del documento que se desean normalizar
928
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
929
     * @version 2016-03-14
930
     */
931
    private function normalizar_41(array &$datos)
932
    {
933
        // completar con nodos por defecto
934
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
935
            'Encabezado' => [
936
                'IdDoc' => false,
937
                'Emisor' => [
938
                    'RUTEmisor' => false,
939
                    'RznSocEmisor' => false,
940
                    'GiroEmisor' => false,
941
                ],
942
                'Receptor' => false,
943
                'Totales' => [
944
                    'MntExe' => 0,
945
                    'MntTotal' => 0,
946
                ]
947
            ],
948
        ], $datos);
949
        // normalizar datos
950
        $this->normalizar_boletas($datos);
951
        $this->normalizar_detalle($datos);
952
        $this->normalizar_aplicar_descuentos_recargos($datos);
953
        $this->normalizar_agregar_IVA_MntTotal($datos);
954
    }
955
956
    /**
957
     * Método que normaliza los datos de una factura de compra electrónica
958
     * @param datos Arreglo con los datos del documento que se desean normalizar
959
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
960
     * @version 2016-02-26
961
     */
962
    private function normalizar_46(array &$datos)
963
    {
964
        // completar con nodos por defecto
965
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
966
            'Encabezado' => [
967
                'IdDoc' => false,
968
                'Emisor' => false,
969
                'Receptor' => false,
970
                'RUTSolicita' => false,
971
                'Totales' => [
972
                    'MntNeto' => 0,
973
                    'MntExe' => false,
974
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
975
                    'IVA' => 0,
976
                    'ImptoReten' => false,
977
                    'IVANoRet' => false,
978
                    'MntTotal' => 0,
979
                ]
980
            ],
981
        ], $datos);
982
        // normalizar datos
983
        $this->normalizar_detalle($datos);
984
        $this->normalizar_aplicar_descuentos_recargos($datos);
985
        $this->normalizar_impuesto_retenido($datos);
986
        $this->normalizar_agregar_IVA_MntTotal($datos);
987
    }
988
989
    /**
990
     * Método que normaliza los datos de una guía de despacho electrónica
991
     * @param datos Arreglo con los datos del documento que se desean normalizar
992
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
993
     * @version 2017-09-01
994
     */
995
    private function normalizar_52(array &$datos)
996
    {
997
        // completar con nodos por defecto
998
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
999
            'Encabezado' => [
1000
                'IdDoc' => false,
1001
                'Emisor' => false,
1002
                'Receptor' => false,
1003
                'RUTSolicita' => false,
1004
                'Transporte' => false,
1005
                'Totales' => [
1006
                    'MntNeto' => 0,
1007
                    'MntExe' => false,
1008
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
1009
                    'IVA' => 0,
1010
                    'ImptoReten' => false,
1011
                    'CredEC' => false,
1012
                    'MntTotal' => 0,
1013
                ]
1014
            ],
1015
        ], $datos);
1016
        // si es traslado interno se copia el emisor en el receptor sólo si el
1017
        // receptor no está definido o bien si el receptor tiene RUT diferente
1018
        // al emisor
1019
        if ($datos['Encabezado']['IdDoc']['IndTraslado']==5) {
1020
            if (!$datos['Encabezado']['Receptor'] or $datos['Encabezado']['Receptor']['RUTRecep']!=$datos['Encabezado']['Emisor']['RUTEmisor']) {
1021
                $datos['Encabezado']['Receptor'] = [];
1022
                $cols = [
1023
                    'RUTEmisor'=>'RUTRecep',
1024
                    'RznSoc'=>'RznSocRecep',
1025
                    'GiroEmis'=>'GiroRecep',
1026
                    'Telefono'=>'Contacto',
1027
                    'CorreoEmisor'=>'CorreoRecep',
1028
                    'DirOrigen'=>'DirRecep',
1029
                    'CmnaOrigen'=>'CmnaRecep',
1030
                ];
1031
                foreach ($cols as $emisor => $receptor) {
1032
                    if (!empty($datos['Encabezado']['Emisor'][$emisor])) {
1033
                        $datos['Encabezado']['Receptor'][$receptor] = $datos['Encabezado']['Emisor'][$emisor];
1034
                    }
1035
                }
1036 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...
1037
                    $datos['Encabezado']['Receptor']['GiroRecep'] = mb_substr($datos['Encabezado']['Receptor']['GiroRecep'], 0, 40);
1038
                }
1039
            }
1040
        }
1041
        // normalizar datos
1042
        $this->normalizar_detalle($datos);
1043
        $this->normalizar_aplicar_descuentos_recargos($datos);
1044
        $this->normalizar_impuesto_retenido($datos);
1045
        $this->normalizar_agregar_IVA_MntTotal($datos);
1046
        $this->normalizar_transporte($datos);
1047
    }
1048
1049
    /**
1050
     * Método que normaliza los datos de una nota de débito
1051
     * @param datos Arreglo con los datos del documento que se desean normalizar
1052
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1053
     * @version 2017-02-23
1054
     */
1055 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...
1056
    {
1057
        // completar con nodos por defecto
1058
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1059
            'Encabezado' => [
1060
                'IdDoc' => false,
1061
                'Emisor' => false,
1062
                'Receptor' => false,
1063
                'RUTSolicita' => false,
1064
                'Totales' => [
1065
                    'MntNeto' => 0,
1066
                    'MntExe' => 0,
1067
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
1068
                    'IVA' => false,
1069
                    'ImptoReten' => false,
1070
                    'IVANoRet' => false,
1071
                    'CredEC' => false,
1072
                    'MntTotal' => 0,
1073
                ]
1074
            ],
1075
        ], $datos);
1076
        // normalizar datos
1077
        $this->normalizar_detalle($datos);
1078
        $this->normalizar_aplicar_descuentos_recargos($datos);
1079
        $this->normalizar_impuesto_retenido($datos);
1080
        $this->normalizar_agregar_IVA_MntTotal($datos);
1081
        if (!$datos['Encabezado']['Totales']['MntNeto']) {
1082
            $datos['Encabezado']['Totales']['MntNeto'] = 0;
1083
            $datos['Encabezado']['Totales']['TasaIVA'] = false;
1084
        }
1085
    }
1086
1087
    /**
1088
     * Método que normaliza los datos de una nota de crédito
1089
     * @param datos Arreglo con los datos del documento que se desean normalizar
1090
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1091
     * @version 2017-02-23
1092
     */
1093 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...
1094
    {
1095
        // completar con nodos por defecto
1096
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1097
            'Encabezado' => [
1098
                'IdDoc' => false,
1099
                'Emisor' => false,
1100
                'Receptor' => false,
1101
                'RUTSolicita' => false,
1102
                'Totales' => [
1103
                    'MntNeto' => 0,
1104
                    'MntExe' => 0,
1105
                    'TasaIVA' => \sasco\LibreDTE\Sii::getIVA(),
1106
                    'IVA' => false,
1107
                    'ImptoReten' => false,
1108
                    'IVANoRet' => false,
1109
                    'CredEC' => false,
1110
                    'MntTotal' => 0,
1111
                ]
1112
            ],
1113
        ], $datos);
1114
        // normalizar datos
1115
        $this->normalizar_detalle($datos);
1116
        $this->normalizar_aplicar_descuentos_recargos($datos);
1117
        $this->normalizar_impuesto_retenido($datos);
1118
        $this->normalizar_agregar_IVA_MntTotal($datos);
1119
        if (!$datos['Encabezado']['Totales']['MntNeto']) {
1120
            $datos['Encabezado']['Totales']['MntNeto'] = 0;
1121
            $datos['Encabezado']['Totales']['TasaIVA'] = false;
1122
        }
1123
    }
1124
1125
    /**
1126
     * Método que normaliza los datos de una factura electrónica de exportación
1127
     * @param datos Arreglo con los datos del documento que se desean normalizar
1128
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1129
     * @version 2016-04-05
1130
     */
1131 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...
1132
    {
1133
        // completar con nodos por defecto
1134
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1135
            'Encabezado' => [
1136
                'IdDoc' => false,
1137
                'Emisor' => false,
1138
                'Receptor' => false,
1139
                'Transporte' => [
1140
                    'Patente' => false,
1141
                    'RUTTrans' => false,
1142
                    'Chofer' => false,
1143
                    'DirDest' => false,
1144
                    'CmnaDest' => false,
1145
                    'CiudadDest' => false,
1146
                    'Aduana' => [
1147
                        'CodModVenta' => false,
1148
                        'CodClauVenta' => false,
1149
                        'TotClauVenta' => false,
1150
                        'CodViaTransp' => false,
1151
                        'NombreTransp' => false,
1152
                        'RUTCiaTransp' => false,
1153
                        'NomCiaTransp' => false,
1154
                        'IdAdicTransp' => false,
1155
                        'Booking' => false,
1156
                        'Operador' => false,
1157
                        'CodPtoEmbarque' => false,
1158
                        'IdAdicPtoEmb' => false,
1159
                        'CodPtoDesemb' => false,
1160
                        'IdAdicPtoDesemb' => false,
1161
                        'Tara' => false,
1162
                        'CodUnidMedTara' => false,
1163
                        'PesoBruto' => false,
1164
                        'CodUnidPesoBruto' => false,
1165
                        'PesoNeto' => false,
1166
                        'CodUnidPesoNeto' => false,
1167
                        'TotItems' => false,
1168
                        'TotBultos' => false,
1169
                        'TipoBultos' => false,
1170
                        'MntFlete' => false,
1171
                        'MntSeguro' => false,
1172
                        'CodPaisRecep' => false,
1173
                        'CodPaisDestin' => false,
1174
                    ],
1175
                ],
1176
                'Totales' => [
1177
                    'TpoMoneda' => null,
1178
                    'MntExe' => 0,
1179
                    'MntTotal' => 0,
1180
                ]
1181
            ],
1182
        ], $datos);
1183
        // normalizar datos
1184
        $this->normalizar_detalle($datos);
1185
        $this->normalizar_aplicar_descuentos_recargos($datos);
1186
        $this->normalizar_impuesto_retenido($datos);
1187
        $this->normalizar_agregar_IVA_MntTotal($datos);
1188
        $this->normalizar_exportacion($datos);
1189
    }
1190
1191
    /**
1192
     * Método que normaliza los datos de una nota de débito de exportación
1193
     * @param datos Arreglo con los datos del documento que se desean normalizar
1194
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1195
     * @version 2016-04-05
1196
     */
1197 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...
1198
    {
1199
        // completar con nodos por defecto
1200
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1201
            'Encabezado' => [
1202
                'IdDoc' => false,
1203
                'Emisor' => false,
1204
                'Receptor' => false,
1205
                'Transporte' => [
1206
                    'Patente' => false,
1207
                    'RUTTrans' => false,
1208
                    'Chofer' => false,
1209
                    'DirDest' => false,
1210
                    'CmnaDest' => false,
1211
                    'CiudadDest' => false,
1212
                    'Aduana' => [
1213
                        'CodModVenta' => false,
1214
                        'CodClauVenta' => false,
1215
                        'TotClauVenta' => false,
1216
                        'CodViaTransp' => false,
1217
                        'NombreTransp' => false,
1218
                        'RUTCiaTransp' => false,
1219
                        'NomCiaTransp' => false,
1220
                        'IdAdicTransp' => false,
1221
                        'Booking' => false,
1222
                        'Operador' => false,
1223
                        'CodPtoEmbarque' => false,
1224
                        'IdAdicPtoEmb' => false,
1225
                        'CodPtoDesemb' => false,
1226
                        'IdAdicPtoDesemb' => false,
1227
                        'Tara' => false,
1228
                        'CodUnidMedTara' => false,
1229
                        'PesoBruto' => false,
1230
                        'CodUnidPesoBruto' => false,
1231
                        'PesoNeto' => false,
1232
                        'CodUnidPesoNeto' => false,
1233
                        'TotItems' => false,
1234
                        'TotBultos' => false,
1235
                        'TipoBultos' => false,
1236
                        'MntFlete' => false,
1237
                        'MntSeguro' => false,
1238
                        'CodPaisRecep' => false,
1239
                        'CodPaisDestin' => false,
1240
                    ],
1241
                ],
1242
                'Totales' => [
1243
                    'TpoMoneda' => null,
1244
                    'MntExe' => 0,
1245
                    'MntTotal' => 0,
1246
                ]
1247
            ],
1248
        ], $datos);
1249
        // normalizar datos
1250
        $this->normalizar_detalle($datos);
1251
        $this->normalizar_aplicar_descuentos_recargos($datos);
1252
        $this->normalizar_impuesto_retenido($datos);
1253
        $this->normalizar_agregar_IVA_MntTotal($datos);
1254
        $this->normalizar_exportacion($datos);
1255
    }
1256
1257
    /**
1258
     * Método que normaliza los datos de una nota de crédito de exportación
1259
     * @param datos Arreglo con los datos del documento que se desean normalizar
1260
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1261
     * @version 2016-04-05
1262
     */
1263 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...
1264
    {
1265
        // completar con nodos por defecto
1266
        $datos = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
1267
            'Encabezado' => [
1268
                'IdDoc' => false,
1269
                'Emisor' => false,
1270
                'Receptor' => false,
1271
                'Transporte' => [
1272
                    'Patente' => false,
1273
                    'RUTTrans' => false,
1274
                    'Chofer' => false,
1275
                    'DirDest' => false,
1276
                    'CmnaDest' => false,
1277
                    'CiudadDest' => false,
1278
                    'Aduana' => [
1279
                        'CodModVenta' => false,
1280
                        'CodClauVenta' => false,
1281
                        'TotClauVenta' => false,
1282
                        'CodViaTransp' => false,
1283
                        'NombreTransp' => false,
1284
                        'RUTCiaTransp' => false,
1285
                        'NomCiaTransp' => false,
1286
                        'IdAdicTransp' => false,
1287
                        'Booking' => false,
1288
                        'Operador' => false,
1289
                        'CodPtoEmbarque' => false,
1290
                        'IdAdicPtoEmb' => false,
1291
                        'CodPtoDesemb' => false,
1292
                        'IdAdicPtoDesemb' => false,
1293
                        'Tara' => false,
1294
                        'CodUnidMedTara' => false,
1295
                        'PesoBruto' => false,
1296
                        'CodUnidPesoBruto' => false,
1297
                        'PesoNeto' => false,
1298
                        'CodUnidPesoNeto' => false,
1299
                        'TotItems' => false,
1300
                        'TotBultos' => false,
1301
                        'TipoBultos' => false,
1302
                        'MntFlete' => false,
1303
                        'MntSeguro' => false,
1304
                        'CodPaisRecep' => false,
1305
                        'CodPaisDestin' => false,
1306
                    ],
1307
                ],
1308
                'Totales' => [
1309
                    'TpoMoneda' => null,
1310
                    'MntExe' => 0,
1311
                    'MntTotal' => 0,
1312
                ]
1313
            ],
1314
        ], $datos);
1315
        // normalizar datos
1316
        $this->normalizar_detalle($datos);
1317
        $this->normalizar_aplicar_descuentos_recargos($datos);
1318
        $this->normalizar_impuesto_retenido($datos);
1319
        $this->normalizar_agregar_IVA_MntTotal($datos);
1320
        $this->normalizar_exportacion($datos);
1321
    }
1322
1323
    /**
1324
     * Método que normaliza los datos de exportacion de un documento
1325
     * @param datos Arreglo con los datos del documento que se desean normalizar
1326
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1327
     * @version 2017-10-15
1328
     */
1329
    public function normalizar_exportacion(array &$datos)
1330
    {
1331
        // agregar modalidad de venta por defecto si no existe
1332
        if (empty($datos['Encabezado']['Transporte']['Aduana']['CodModVenta']) and (!isset($datos['Encabezado']['IdDoc']['IndServicio']) or !in_array($datos['Encabezado']['IdDoc']['IndServicio'], [3, 4, 5]))) {
1333
            $datos['Encabezado']['Transporte']['Aduana']['CodModVenta'] = 1;
1334
        }
1335
        // quitar campos que no son parte del documento de exportacion
1336
        $datos['Encabezado']['Receptor']['CmnaRecep'] = false;
1337
        // colocar forma de pago de exportación
1338
        if (!empty($datos['Encabezado']['IdDoc']['FmaPago'])) {
1339
            $formas = [3 => 21];
1340
            if (isset($formas[$datos['Encabezado']['IdDoc']['FmaPago']])) {
1341
                $datos['Encabezado']['IdDoc']['FmaPagExp'] = $formas[$datos['Encabezado']['IdDoc']['FmaPago']];
1342
            }
1343
            $datos['Encabezado']['IdDoc']['FmaPago'] = false;
1344
        }
1345
        // si es entrega gratuita se coloca el tipo de cambio en CLP en 0 para que total sea 0
1346
        if (!empty($datos['Encabezado']['IdDoc']['FmaPagExp']) and $datos['Encabezado']['IdDoc']['FmaPagExp']==21 and !empty($datos['Encabezado']['OtraMoneda'])) {
1347 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...
1348
                $datos['Encabezado']['OtraMoneda'] = [$datos['Encabezado']['OtraMoneda']];
1349
            }
1350
            foreach ($datos['Encabezado']['OtraMoneda'] as &$OtraMoneda) {
1351
                if ($OtraMoneda['TpoMoneda']=='PESO CL') {
1352
                    $OtraMoneda['TpoCambio'] = 0;
1353
                }
1354
            }
1355
        }
1356
    }
1357
1358
    /**
1359
     * Método que normaliza los detalles del documento
1360
     * @param datos Arreglo con los datos del documento que se desean normalizar
1361
     * @warning Revisar como se aplican descuentos y recargos, ¿debería ser un porcentaje del monto original?
1362
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1363
     * @version 2017-07-24
1364
     */
1365
    private function normalizar_detalle(array &$datos)
1366
    {
1367
        if (!isset($datos['Detalle'][0]))
1368
            $datos['Detalle'] = [$datos['Detalle']];
1369
        $item = 1;
1370
        foreach ($datos['Detalle'] as &$d) {
1371
            $d = array_merge([
1372
                'NroLinDet' => $item++,
1373
                'CdgItem' => false,
1374
                'IndExe' => false,
1375
                'Retenedor' => false,
1376
                'NmbItem' => false,
1377
                'DscItem' => false,
1378
                'QtyRef' => false,
1379
                'UnmdRef' => false,
1380
                'PrcRef' => false,
1381
                'QtyItem' => false,
1382
                'Subcantidad' => false,
1383
                'FchElabor' => false,
1384
                'FchVencim' => false,
1385
                'UnmdItem' => false,
1386
                'PrcItem' => false,
1387
                'DescuentoPct' => false,
1388
                'DescuentoMonto' => false,
1389
                'RecargoPct' => false,
1390
                'RecargoMonto' => false,
1391
                'CodImpAdic' => false,
1392
                'MontoItem' => false,
1393
            ], $d);
1394
            // corregir datos
1395
            $d['NmbItem'] = mb_substr($d['NmbItem'], 0, 80);
1396
            if (!empty($d['DscItem'])) {
1397
                $d['DscItem'] = mb_substr($d['DscItem'], 0, 1000);
1398
            }
1399
            // normalizar
1400
            if ($this->esExportacion()) {
1401
                $d['IndExe'] = 1;
1402
            }
1403
            if (is_array($d['CdgItem'])) {
1404
                $d['CdgItem'] = array_merge([
1405
                    'TpoCodigo' => false,
1406
                    'VlrCodigo' => false,
1407
                ], $d['CdgItem']);
1408
                if ($d['Retenedor']===false and $d['CdgItem']['TpoCodigo']=='CPCS') {
1409
                    $d['Retenedor'] = true;
1410
                }
1411
            }
1412
            if ($d['Retenedor']!==false) {
1413
                if (!is_array($d['Retenedor'])) {
1414
                    $d['Retenedor'] = ['IndAgente'=>'R'];
1415
                }
1416
                $d['Retenedor'] = array_merge([
1417
                    'IndAgente' => 'R',
1418
                    'MntBaseFaena' => false,
1419
                    'MntMargComer' => false,
1420
                    'PrcConsFinal' => false,
1421
                ], $d['Retenedor']);
1422
            }
1423
            if ($d['CdgItem']!==false and !is_array($d['CdgItem'])) {
1424
                $d['CdgItem'] = [
1425
                    'TpoCodigo' => empty($d['Retenedor']['IndAgente']) ? 'INT1' : 'CPCS',
1426
                    'VlrCodigo' => $d['CdgItem'],
1427
                ];
1428
            }
1429
            if ($d['PrcItem']) {
1430
                if (!$d['QtyItem'])
1431
                    $d['QtyItem'] = 1;
1432
                if (empty($d['MontoItem'])) {
1433
                    $d['MontoItem'] = $this->round(
1434
                        (float)$d['QtyItem'] * (float)$d['PrcItem'],
0 ignored issues
show
Documentation introduced by
(double) $d['QtyItem'] * (double) $d['PrcItem'] is of type 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...
1435
                        $datos['Encabezado']['Totales']['TpoMoneda']
1436
                    );
1437
                    // aplicar descuento
1438
                    if ($d['DescuentoPct']) {
1439
                        $d['DescuentoMonto'] = round($d['MontoItem'] * (float)$d['DescuentoPct']/100);
1440
                    }
1441
                    $d['MontoItem'] -= $d['DescuentoMonto'];
1442
                    // aplicar recargo
1443
                    if ($d['RecargoPct']) {
1444
                        $d['RecargoMonto'] = round($d['MontoItem'] * (float)$d['RecargoPct']/100);
1445
                    }
1446
                    $d['MontoItem'] += $d['RecargoMonto'];
1447
                    // aproximar monto del item
1448
                    $d['MontoItem'] = $this->round(
1449
                        $d['MontoItem'], $datos['Encabezado']['Totales']['TpoMoneda']
1450
                    );
1451
                }
1452
            } else if (empty($d['MontoItem'])) {
1453
                $d['MontoItem'] = 0;
1454
            }
1455
            // sumar valor del monto a MntNeto o MntExe según corresponda
1456
            if ($d['MontoItem']) {
1457
                // si no es boleta
1458
                if (!$this->esBoleta()) {
1459
                    if ((!isset($datos['Encabezado']['Totales']['MntNeto']) or $datos['Encabezado']['Totales']['MntNeto']===false) and isset($datos['Encabezado']['Totales']['MntExe'])) {
1460
                        $datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
1461 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...
1462
                        if (!empty($d['IndExe'])) {
1463
                            if ($d['IndExe']==1) {
1464
                                $datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
1465
                            }
1466
                        } else {
1467
                            $datos['Encabezado']['Totales']['MntNeto'] += $d['MontoItem'];
1468
                        }
1469
                    }
1470
                }
1471
                // si es boleta
1472 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...
1473
                    // si es exento
1474
                    if (!empty($d['IndExe'])) {
1475
                        if ($d['IndExe']==1) {
1476
                            $datos['Encabezado']['Totales']['MntExe'] += $d['MontoItem'];
1477
                        }
1478
                    }
1479
                    // agregar al monto total
1480
                    $datos['Encabezado']['Totales']['MntTotal'] += $d['MontoItem'];
1481
                }
1482
            }
1483
        }
1484
    }
1485
1486
    /**
1487
     * Método que aplica los descuentos y recargos generales respectivos a los
1488
     * montos que correspondan según e indicador del descuento o recargo
1489
     * @param datos Arreglo con los datos del documento que se desean normalizar
1490
     * @warning Boleta afecta con algún item exento el descuento se podría estar aplicando mal
1491
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1492
     * @version 2017-09-06
1493
     */
1494
    private function normalizar_aplicar_descuentos_recargos(array &$datos)
1495
    {
1496
        if (!empty($datos['DscRcgGlobal'])) {
1497 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...
1498
                $datos['DscRcgGlobal'] = [$datos['DscRcgGlobal']];
1499
            foreach ($datos['DscRcgGlobal'] as &$dr) {
1500
                $dr = array_merge([
1501
                    'NroLinDR' => false,
1502
                    'TpoMov' => false,
1503
                    'GlosaDR' => false,
1504
                    'TpoValor' => false,
1505
                    'ValorDR' => false,
1506
                    'ValorDROtrMnda' => false,
1507
                    'IndExeDR' => false,
1508
                ], $dr);
1509
                if ($this->esExportacion()) {
1510
                    $dr['IndExeDR'] = 1;
1511
                }
1512
                // determinar a que aplicar el descuento/recargo
1513
                if (!isset($dr['IndExeDR']) or $dr['IndExeDR']===false) {
1514
                    $monto = $this->getTipo()==39 ? 'MntTotal' : 'MntNeto';
1515
                } else if ($dr['IndExeDR']==1) {
1516
                    $monto = 'MntExe';
1517
                } else if ($dr['IndExeDR']==2) {
1518
                    $monto = 'MontoNF';
1519
                }
1520
                // si no hay monto al que aplicar el descuento se omite
1521
                if (empty($datos['Encabezado']['Totales'][$monto])) {
1522
                    continue;
1523
                }
1524
                // calcular valor del descuento o recargo
1525
                if ($dr['TpoValor']=='$') {
1526
                    $dr['ValorDR'] = $this->round($dr['ValorDR'], $datos['Encabezado']['Totales']['TpoMoneda'], 2);
1527
                }
1528
                $valor =
1529
                    $dr['TpoValor']=='%'
1530
                    ? $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...
1531
                    : $dr['ValorDR']
1532
                ;
1533
                // aplicar descuento
1534
                if ($dr['TpoMov']=='D') {
1535
                    $datos['Encabezado']['Totales'][$monto] -= $valor;
1536
                }
1537
                // aplicar recargo
1538
                else if ($dr['TpoMov']=='R') {
1539
                    $datos['Encabezado']['Totales'][$monto] += $valor;
1540
                }
1541
                $datos['Encabezado']['Totales'][$monto] = $this->round(
1542
                    $datos['Encabezado']['Totales'][$monto],
1543
                    $datos['Encabezado']['Totales']['TpoMoneda']
1544
                );
1545
                // si el descuento global se aplica a una boleta exenta se copia el valor exento al total
1546
                if ($this->getTipo()==41 and isset($dr['IndExeDR']) and $dr['IndExeDR']==1) {
1547
                    $datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntExe'];
1548
                }
1549
            }
1550
        }
1551
    }
1552
1553
    /**
1554
     * Método que calcula los montos de impuestos adicionales o retenciones
1555
     * @param datos Arreglo con los datos del documento que se desean normalizar
1556
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1557
     * @version 2016-04-05
1558
     */
1559
    private function normalizar_impuesto_retenido(array &$datos)
1560
    {
1561
        // copiar montos
1562
        $montos = [];
1563
        foreach ($datos['Detalle'] as &$d) {
1564
            if (!empty($d['CodImpAdic'])) {
1565
                if (!isset($montos[$d['CodImpAdic']]))
1566
                    $montos[$d['CodImpAdic']] = 0;
1567
                $montos[$d['CodImpAdic']] += $d['MontoItem'];
1568
            }
1569
        }
1570
        // si hay montos y no hay total para impuesto retenido se arma
1571
        if (!empty($montos)) {
1572 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...
1573
                $datos['Encabezado']['Totales']['ImptoReten'] = [];
1574
            } else if (!isset($datos['Encabezado']['Totales']['ImptoReten'][0])) {
1575
                $datos['Encabezado']['Totales']['ImptoReten'] = [$datos['Encabezado']['Totales']['ImptoReten']];
1576
            }
1577
        }
1578
        // armar impuesto adicional o retención en los totales
1579
        foreach ($montos as $codigo => $neto) {
1580
            // buscar si existe el impuesto en los totales
1581
            $i = 0;
1582
            foreach ($datos['Encabezado']['Totales']['ImptoReten'] as &$ImptoReten) {
1583
                if ($ImptoReten['TipoImp']==$codigo) {
1584
                    break;
1585
                }
1586
                $i++;
1587
            }
1588
            // si no existe se crea
1589 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...
1590
                $datos['Encabezado']['Totales']['ImptoReten'][] = [
1591
                    'TipoImp' => $codigo
1592
                ];
1593
            }
1594
            // se normaliza
1595
            $datos['Encabezado']['Totales']['ImptoReten'][$i] = array_merge([
1596
                'TipoImp' => $codigo,
1597
                'TasaImp' => ImpuestosAdicionales::getTasa($codigo),
1598
                'MontoImp' => null,
1599
            ], $datos['Encabezado']['Totales']['ImptoReten'][$i]);
1600
            // si el monto no existe se asigna
1601
            if ($datos['Encabezado']['Totales']['ImptoReten'][$i]['MontoImp']===null) {
1602
                $datos['Encabezado']['Totales']['ImptoReten'][$i]['MontoImp'] = round(
1603
                    $neto * $datos['Encabezado']['Totales']['ImptoReten'][$i]['TasaImp']/100
1604
                );
1605
            }
1606
        }
1607
        // quitar los codigos que no existen en el detalle
1608
        if (isset($datos['Encabezado']['Totales']['ImptoReten']) and is_array($datos['Encabezado']['Totales']['ImptoReten'])) {
1609
            $codigos = array_keys($montos);
1610
            $n_impuestos = count($datos['Encabezado']['Totales']['ImptoReten']);
1611
            for ($i=0; $i<$n_impuestos; $i++) {
1612 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...
1613
                    unset($datos['Encabezado']['Totales']['ImptoReten'][$i]);
1614
                }
1615
            }
1616
            sort($datos['Encabezado']['Totales']['ImptoReten']);
1617
        }
1618
    }
1619
1620
    /**
1621
     * Método que calcula el monto del IVA y el monto total del documento a
1622
     * partir del monto neto y la tasa de IVA si es que existe
1623
     * @param datos Arreglo con los datos del documento que se desean normalizar
1624
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1625
     * @version 2020-10-12
1626
     */
1627
    private function normalizar_agregar_IVA_MntTotal(array &$datos)
1628
    {
1629
        // si es una boleta y no están los datos de monto neto ni IVA se obtienen
1630
        // WARNING: no considera los casos donde hay impuestos adicionales en las boletas
1631
        //          si la boleta tiene impuestos adicionales, se deben indicar MntNeto e IVA
1632
        //          y no se usará esta parte de la normalización
1633
        // valor IndMntNeto = 2 indica que los montosde las líneas on netos en cuyo caso no aplica el cálculo
1634
        // de neto e iva a partir del total y deberá venir informado de otra forma (aun no definido)
1635
        if ($this->esBoleta() and (empty($datos['Encabezado']['IdDoc']['IndMntNeto']) or $datos['Encabezado']['IdDoc']['IndMntNeto']!=2)) {
1636
            $total = (int)$datos['Encabezado']['Totales']['MntTotal'] - (int)$datos['Encabezado']['Totales']['MntExe'];
1637
            if ($total and (empty($datos['Encabezado']['Totales']['MntNeto']) or empty($datos['Encabezado']['Totales']['IVA']))) {
1638
                list($datos['Encabezado']['Totales']['MntNeto'], $datos['Encabezado']['Totales']['IVA']) = $this->calcularNetoIVA($total);
0 ignored issues
show
Documentation introduced by
$total is of type integer, 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...
1639
            }
1640
        }
1641
        // agregar IVA y monto total
1642
        if (!empty($datos['Encabezado']['Totales']['MntNeto'])) {
1643
            if ($datos['Encabezado']['IdDoc']['MntBruto']==1) {
1644
                list($datos['Encabezado']['Totales']['MntNeto'], $datos['Encabezado']['Totales']['IVA']) = $this->calcularNetoIVA(
1645
                    $datos['Encabezado']['Totales']['MntNeto'],
1646
                    $datos['Encabezado']['Totales']['TasaIVA']
1647
                );
1648
            } else {
1649
                if (empty($datos['Encabezado']['Totales']['IVA']) and !empty($datos['Encabezado']['Totales']['TasaIVA'])) {
1650
                    $datos['Encabezado']['Totales']['IVA'] = round(
1651
                        $datos['Encabezado']['Totales']['MntNeto']*($datos['Encabezado']['Totales']['TasaIVA']/100)
1652
                    );
1653
                }
1654
            }
1655
            if (empty($datos['Encabezado']['Totales']['MntTotal'])) {
1656
                $datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntNeto'];
1657
                if (!empty($datos['Encabezado']['Totales']['IVA'])) {
1658
                    $datos['Encabezado']['Totales']['MntTotal'] += $datos['Encabezado']['Totales']['IVA'];
1659
                }
1660
                if (!empty($datos['Encabezado']['Totales']['MntExe'])) {
1661
                    $datos['Encabezado']['Totales']['MntTotal'] += $datos['Encabezado']['Totales']['MntExe'];
1662
                }
1663
            }
1664 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...
1665
            if (!$datos['Encabezado']['Totales']['MntTotal'] and !empty($datos['Encabezado']['Totales']['MntExe'])) {
1666
                $datos['Encabezado']['Totales']['MntTotal'] = $datos['Encabezado']['Totales']['MntExe'];
1667
            }
1668
        }
1669
        // si hay impuesto retenido o adicional se contabiliza en el total
1670
        if (!empty($datos['Encabezado']['Totales']['ImptoReten'])) {
1671
            foreach ($datos['Encabezado']['Totales']['ImptoReten'] as &$ImptoReten) {
1672
                // si es retención se resta al total y se traspasaa IVA no retenido
1673
                // en caso que corresponda
1674
                if (ImpuestosAdicionales::getTipo($ImptoReten['TipoImp'])=='R') {
1675
                    $datos['Encabezado']['Totales']['MntTotal'] -= $ImptoReten['MontoImp'];
1676
                    if ($ImptoReten['MontoImp']!=$datos['Encabezado']['Totales']['IVA']) {
1677
                        $datos['Encabezado']['Totales']['IVANoRet'] = $datos['Encabezado']['Totales']['IVA'] - $ImptoReten['MontoImp'];
1678
                    }
1679
                }
1680
                // si es adicional se suma al total
1681
                else if (ImpuestosAdicionales::getTipo($ImptoReten['TipoImp'])=='A' and isset($ImptoReten['MontoImp'])) {
1682
                    $datos['Encabezado']['Totales']['MntTotal'] += $ImptoReten['MontoImp'];
1683
                }
1684
            }
1685
        }
1686
        // si hay impuesto de crédito a constructoras del 65% se descuenta del total
1687
        if (!empty($datos['Encabezado']['Totales']['CredEC'])) {
1688
            if ($datos['Encabezado']['Totales']['CredEC']===true) {
1689
                $datos['Encabezado']['Totales']['CredEC'] = round($datos['Encabezado']['Totales']['IVA'] * 0.65); // TODO: mover a constante o método
1690
            }
1691
            $datos['Encabezado']['Totales']['MntTotal'] -= $datos['Encabezado']['Totales']['CredEC'];
1692
        }
1693
    }
1694
1695
    /**
1696
     * Método que normaliza los datos de transporte
1697
     * @param datos Arreglo con los datos del documento que se desean normalizar
1698
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1699
     * @version 2017-09-01
1700
     */
1701
    private function normalizar_transporte(array &$datos)
1702
    {
1703
        if (!empty($datos['Encabezado']['Transporte'])) {
1704
            $datos['Encabezado']['Transporte'] = array_merge([
1705
                'Patente' => false,
1706
                'RUTTrans' => false,
1707
                'Chofer' => false,
1708
                'DirDest' => false,
1709
                'CmnaDest' => false,
1710
                'CiudadDest' => false,
1711
                'Aduana' => false,
1712
            ], $datos['Encabezado']['Transporte']);
1713
        }
1714
    }
1715
1716
    /**
1717
     * Método que normaliza las boletas electrónicas, dte 39 y 41
1718
     * @param datos Arreglo con los datos del documento que se desean normalizar
1719
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1720
     * @version 2020-10-11
1721
     */
1722
    private function normalizar_boletas(array &$datos)
1723
    {
1724
        // cambiar tags de DTE a boleta si se pasaron
1725 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...
1726
            $datos['Encabezado']['Emisor']['RznSocEmisor'] = $datos['Encabezado']['Emisor']['RznSoc'];
1727
            $datos['Encabezado']['Emisor']['RznSoc'] = false;
1728
        }
1729 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...
1730
            $datos['Encabezado']['Emisor']['GiroEmisor'] = $datos['Encabezado']['Emisor']['GiroEmis'];
1731
            $datos['Encabezado']['Emisor']['GiroEmis'] = false;
1732
        }
1733
        $datos['Encabezado']['Emisor']['Acteco'] = false;
1734
        $datos['Encabezado']['Emisor']['Telefono'] = false;
1735
        $datos['Encabezado']['Emisor']['CorreoEmisor'] = false;
1736
        $datos['Encabezado']['Emisor']['CdgVendedor'] = false;
1737
        $datos['Encabezado']['Receptor']['GiroRecep'] = false;
1738
        if (!empty($datos['Encabezado']['Receptor']['CorreoRecep'])) {
1739
            $datos['Referencia'][] = [
1740
                'NroLinRef' => !empty($datos['Referencia']) ? (count($datos['Referencia'])+1) : 1,
1741
                'RazonRef' => mb_substr('Email receptor: '.$datos['Encabezado']['Receptor']['CorreoRecep'], 0, 90),
1742
            ];
1743
        }
1744
        $datos['Encabezado']['Receptor']['CorreoRecep'] = false;
1745
        // quitar otros tags que no son parte de las boletas
1746
        $datos['Encabezado']['IdDoc']['FmaPago'] = false;
1747
        $datos['Encabezado']['IdDoc']['FchCancel'] = false;
1748
        $datos['Encabezado']['IdDoc']['MedioPago'] = false;
1749
        $datos['Encabezado']['IdDoc']['TpoCtaPago'] = false;
1750
        $datos['Encabezado']['IdDoc']['NumCtaPago'] = false;
1751
        $datos['Encabezado']['IdDoc']['BcoPago'] = false;
1752
        $datos['Encabezado']['IdDoc']['TermPagoGlosa'] = false;
1753
        $datos['Encabezado']['RUTSolicita'] = false;
1754
        $datos['Encabezado']['IdDoc']['TpoTranCompra'] = false;
1755
        $datos['Encabezado']['IdDoc']['TpoTranVenta'] = false;
1756
        $datos['Encabezado']['Transporte'] = false;
1757
        // ajustar las referencias si existen
1758
        if (!empty($datos['Referencia'])) {
1759 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...
1760
                $datos['Referencia'] = [$datos['Referencia']];
1761
            }
1762
            foreach ($datos['Referencia'] as &$r) {
1763
                foreach (['FchRef'] as $c) {
1764
                    if (isset($r[$c])) {
1765
                        unset($r[$c]);
1766
                    }
1767
                }
1768
            }
1769
        }
1770
    }
1771
1772
    /**
1773
     * Método que redondea valores. Si los montos son en pesos chilenos se
1774
     * redondea, si no se mantienen todos los decimales
1775
     * @param valor Valor que se desea redondear
1776
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1777
     * @version 2016-04-05
1778
     */
1779
    private function round($valor, $moneda = false, $decimal = 4)
1780
    {
1781
        return (!$moneda or $moneda=='PESO CL') ? (int)round($valor) : (float)round($valor, $decimal);
1782
    }
1783
1784
    /**
1785
     * Método que determina el estado de validación sobre el DTE, se verifica:
1786
     *  - Firma del DTE
1787
     *  - RUT del emisor (si se pasó uno para comparar)
1788
     *  - RUT del receptor (si se pasó uno para comparar)
1789
     * @return Código del estado de la validación
1790
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1791
     * @version 2019-07-03
1792
     */
1793
    public function getEstadoValidacion(array $datos = null)
1794
    {
1795
        if (!$this->checkFirma()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->checkFirma() of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
1796
            return 1;
1797
        }
1798
        if (is_array($datos)) {
1799
            if (isset($datos['RUTEmisor']) and $this->getEmisor()!=$datos['RUTEmisor']) {
1800
                return 2;
1801
            }
1802
            if (isset($datos['RUTRecep']) and $this->getReceptor()!=$datos['RUTRecep']) {
1803
                return 3;
1804
            }
1805
        }
1806
        return 0;
1807
    }
1808
1809
    /**
1810
     * Método que indica si la firma del DTE es o no válida
1811
     * @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...
1812
     * @warning No se está verificando el valor del DigestValue del documento (sólo la firma de ese DigestValue)
1813
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1814
     * @version 2020-08-06
1815
     */
1816
    public function checkFirma()
1817
    {
1818
        if (!$this->xml) {
1819
            return null;
1820
        }
1821
        // obtener firma
1822
        $Signature = $this->xml->documentElement->getElementsByTagName('Signature')->item(0);
1823
        // preparar documento a validar
1824
        $D = $this->xml->documentElement->getElementsByTagName($this->tipo_general)->item(0);
1825
        $Documento = new \sasco\LibreDTE\XML();
1826
        $Documento->loadXML($D->C14N());
1827
        $Documento->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
1828
        $SignedInfo = new \sasco\LibreDTE\XML();
1829
        $SignedInfo->loadXML($Signature->getElementsByTagName('SignedInfo')->item(0)->C14N());
1830
        $SignedInfo->documentElement->removeAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi');
1831
        $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...
1832
        $SignatureValue = trim(str_replace(["\n", ' ', "\t"], '', $Signature->getElementsByTagName('SignatureValue')->item(0)->nodeValue));
1833
        $X509Certificate = trim(str_replace(["\n", ' ', "\t"], '', $Signature->getElementsByTagName('X509Certificate')->item(0)->nodeValue));
1834
        $X509Certificate = '-----BEGIN CERTIFICATE-----'."\n".wordwrap($X509Certificate, 64, "\n", true)."\n".'-----END CERTIFICATE----- ';
1835
        $valid = openssl_verify($SignedInfo->C14N(), base64_decode($SignatureValue), $X509Certificate) === 1 ? true : false;
1836
        return $valid;
1837
        //return $valid and $DigestValue===base64_encode(sha1($Documento->C14N(), true));
1838
    }
1839
1840
    /**
1841
     * Método que indica si el documento es o no cedible
1842
     * @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...
1843
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1844
     * @version 2015-09-10
1845
     */
1846
    public function esCedible()
1847
    {
1848
        return !in_array($this->getTipo(), $this->noCedibles);
1849
    }
1850
1851
    /**
1852
     * Método que indica si el documento es o no una boleta electrónica
1853
     * @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...
1854
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1855
     * @version 2015-12-11
1856
     */
1857
    public function esBoleta()
1858
    {
1859
        return in_array($this->getTipo(), [39, 41]);
1860
    }
1861
1862
    /**
1863
     * Método que indica si el documento es o no una exportación
1864
     * @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...
1865
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1866
     * @version 2016-04-05
1867
     */
1868
    public function esExportacion()
1869
    {
1870
        return in_array($this->getTipo(), $this->tipos['Exportaciones']);
1871
    }
1872
1873
    /**
1874
     * Método que valida el schema del DTE
1875
     * @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...
1876
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1877
     * @version 2015-12-15
1878
     */
1879
    public function schemaValidate()
1880
    {
1881
        return true;
1882
    }
1883
1884
    /**
1885
     * Método que valida los datos del DTE
1886
     * @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...
1887
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1888
     * @version 2020-03-13
1889
     */
1890
    public function verificarDatos()
1891
    {
1892
        if (class_exists('\sasco\LibreDTE\Extra\Sii\Dte\VerificadorDatos')) {
1893
            if (!\sasco\LibreDTE\Extra\Sii\Dte\VerificadorDatos::check($this->getDatos())) {
1894
                return false;
1895
            }
1896
        }
1897
        return true;
1898
    }
1899
1900
    /**
1901
     * Método que obtiene el estado del DTE
1902
     * @param Firma objeto que representa la Firma Electrónca
1903
     * @return Arreglo con el estado del DTE
1904
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1905
     * @version 2015-10-24
1906
     */
1907
    public function getEstado(\sasco\LibreDTE\FirmaElectronica $Firma)
1908
    {
1909
        // solicitar token
1910
        $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...
1911
        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...
1912
            return false;
1913
        }
1914
        // consultar estado dte
1915
        $run = $Firma->getID();
1916
        if ($run===false) {
1917
            return false;
1918
        }
1919
        list($RutConsultante, $DvConsultante) = explode('-', $run);
1920
        list($RutCompania, $DvCompania) = explode('-', $this->getEmisor());
1921
        list($RutReceptor, $DvReceptor) = explode('-', $this->getReceptor());
1922
        list($Y, $m, $d) = explode('-', $this->getFechaEmision());
1923
        $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...
1924
            'RutConsultante'  => $RutConsultante,
1925
            'DvConsultante'   => $DvConsultante,
1926
            'RutCompania'     => $RutCompania,
1927
            'DvCompania'      => $DvCompania,
1928
            'RutReceptor'     => $RutReceptor,
1929
            'DvReceptor'      => $DvReceptor,
1930
            'TipoDte'         => $this->getTipo(),
1931
            'FolioDte'        => $this->getFolio(),
1932
            'FechaEmisionDte' => $d.$m.$Y,
1933
            'MontoDte'        => $this->getMontoTotal(),
1934
            'token'           => $token,
1935
        ]);
1936
        // si el estado se pudo recuperar se muestra
1937
        if ($xml===false) {
1938
            return false;
1939
        }
1940
        // entregar estado
1941
        return (array)$xml->xpath('/SII:RESPUESTA/SII:RESP_HDR')[0];
1942
    }
1943
1944
    /**
1945
     * Método que obtiene el estado avanzado del DTE
1946
     * @param Firma objeto que representa la Firma Electrónca
1947
     * @return Arreglo con el estado del DTE
1948
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1949
     * @version 2016-08-05
1950
     */
1951
    public function getEstadoAvanzado(\sasco\LibreDTE\FirmaElectronica $Firma)
1952
    {
1953
        // solicitar token
1954
        $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...
1955
        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...
1956
            return false;
1957
        }
1958
        // consultar estado dte
1959
        list($RutEmpresa, $DvEmpresa) = explode('-', $this->getEmisor());
1960
        list($RutReceptor, $DvReceptor) = explode('-', $this->getReceptor());
1961
        list($Y, $m, $d) = explode('-', $this->getFechaEmision());
1962
        $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...
1963
            'RutEmpresa'      => $RutEmpresa,
1964
            'DvEmpresa'       => $DvEmpresa,
1965
            'RutReceptor'     => $RutReceptor,
1966
            'DvReceptor'      => $DvReceptor,
1967
            'TipoDte'         => $this->getTipo(),
1968
            'FolioDte'        => $this->getFolio(),
1969
            'FechaEmisionDte' => $d.'-'.$m.'-'.$Y,
1970
            'MontoDte'        => $this->getMontoTotal(),
1971
            'FirmaDte'        => str_replace("\n", '', $this->getFirma()['SignatureValue']),
1972
            'token'           => $token,
1973
        ]);
1974
        // si el estado se pudo recuperar se muestra
1975
        if ($xml===false) {
1976
            return false;
1977
        }
1978
        // entregar estado
1979
        return (array)$xml->xpath('/SII:RESPUESTA/SII:RESP_BODY')[0];
1980
    }
1981
1982
    /**
1983
     * Método que entrega la última acción registrada para el DTE en el registro de compra y venta
1984
     * @return Arreglo con los datos de la última acción
1985
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
1986
     * @version 2017-08-29
1987
     */
1988
    public function getUltimaAccionRCV(\sasco\LibreDTE\FirmaElectronica $Firma)
1989
    {
1990
        list($emisor_rut, $emisor_dv) = explode('-', $this->getEmisor());
1991
        $RCV = new \sasco\LibreDTE\Sii\RegistroCompraVenta($Firma);
1992
        try {
1993
            $eventos = $RCV->listarEventosHistDoc($emisor_rut, $emisor_dv, $this->getTipo(), $this->getFolio());
1994
            return $eventos ? $eventos[count($eventos)-1] : null;
1995
        } catch (\Exception $e) {
1996
            return null;
1997
        }
1998
    }
1999
2000
}
2001