Completed
Push — master ( 6d6e59...37efbc )
by Esteban De La Fuente
01:43
created

Cesion::schemaValidate()   A

Complexity

Conditions 1
Paths 1

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 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * LibreDTE
5
 * Copyright (C) SASCO SpA (https://sasco.cl)
6
 *
7
 * Este programa es software libre: usted puede redistribuirlo y/o
8
 * modificarlo bajo los términos de la Licencia Pública General Affero de GNU
9
 * publicada por la Fundación para el Software Libre, ya sea la versión
10
 * 3 de la Licencia, o (a su elección) cualquier versión posterior de la
11
 * misma.
12
 *
13
 * Este programa se distribuye con la esperanza de que sea útil, pero
14
 * SIN GARANTÍA ALGUNA; ni siquiera la garantía implícita
15
 * MERCANTIL o de APTITUD PARA UN PROPÓSITO DETERMINADO.
16
 * Consulte los detalles de la Licencia Pública General Affero de GNU para
17
 * obtener una información más detallada.
18
 *
19
 * Debería haber recibido una copia de la Licencia Pública General Affero de GNU
20
 * junto a este programa.
21
 * En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
22
 */
23
24
namespace sasco\LibreDTE\Sii\Factoring;
25
26
/**
27
 * Clase que representa la cesion electrónica
28
 * @author Adonias Vasquez (adonias.vasquez[at]epys.cl)
29
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
30
 * @version 2016-12-30
31
 */
32
class Cesion
33
{
34
35
    private $Encabezado; ///< Encabezado del DTE que se está cediendo
36
    private $datos; ///< Datos del XML de cesión
37
    private $declaracion = 'Yo, {usuario_nombre}, RUN {usuario_run}, representando a {emisor_razon_social}, RUT {emisor_rut}, declaro que he puesto a disposición del cesionario {cesionario_razon_social}, RUT {cesionario_rut}, el documento donde constan los recibos de la recepción de mercaderías entregadas o servicios prestados, entregados por parte del deudor de la factura {receptor_razon_social}, RUT {receptor_rut}, de acuerdo a lo establecido en la Ley N° 19.983'; ///< Declaración estándar en caso que no sea indicada al momento de crear al cedente
38
39
    /**
40
     * Constructor de la clase Cesion
41
     * @param DTECedido Objeto DteCedido
42
     * @param Seq secuencia de la cesión
43
     * @author Adonias Vasquez (adonias.vasquez[at]epys.cl)
44
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
45
     * @version 2020-07-27
46
     */
47
    public function __construct(DteCedido $DTECedido = null, $Seq = 1)
48
    {
49
        if (!empty($DTECedido)) {
50
            $this->Encabezado = $DTECedido->getDTE()->getDatos()['Encabezado'];
51
            $this->datos = [
52
                'Cesion' => [
53
                    '@attributes' => [
54
                        'xmlns' => 'http://www.sii.cl/SiiDte',
55
                        'version' => '1.0'
56
                    ],
57
                    'DocumentoCesion' => [
58
                        '@attributes' => [
59
                            'ID' => 'LibreDTE_Cesion',
60
                        ],
61
                        'SeqCesion' => $Seq,
62
                        'IdDTE' => [
63
                            'TipoDTE' => $this->Encabezado['IdDoc']['TipoDTE'],
64
                            'RUTEmisor' => $this->Encabezado['Emisor']['RUTEmisor'],
65
                            'RUTReceptor' => $this->Encabezado['Receptor']['RUTRecep'],
66
                            'Folio' => $this->Encabezado['IdDoc']['Folio'],
67
                            'FchEmis' => $this->Encabezado['IdDoc']['FchEmis'],
68
                            'MntTotal' => $this->Encabezado['Totales']['MntTotal'],
69
                        ],
70
                        'Cedente' => false,
71
                        'Cesionario' => false,
72
                        'MontoCesion' => $this->Encabezado['Totales']['MntTotal'],
73
                        'UltimoVencimiento' =>
74
                            isset($this->Encabezado['IdDoc']['MntPagos']['FchPago'])
75
                            ? $this->Encabezado['IdDoc']['MntPagos']['FchPago']
76
                            : $this->Encabezado['IdDoc']['FchEmis'],
77
                        'OtrasCondiciones' => false,
78
                        'eMailDeudor' => false,
79
                        'TmstCesion' => date('Y-m-d\TH:i:s')
80
                    ]
81
                ]
82
            ];
83
        }
84
    }
85
86
    /**
87
     * Método que permite cambiar la declaración por defecto
88
     * Están disponibles las siguientes variables dentro del string de la declaración:
89
     *   - {usuario_nombre}
90
     *   - {usuario_run}
91
     *   - {emisor_razon_social}
92
     *   - {emisor_rut}
93
     *   - {cesionario_razon_social}
94
     *   - {cesionario_rut}
95
     *   - {receptor_razon_social}
96
     *   - {receptor_rut}
97
     * @param declaracion String con la declaración y las variables para poder reemplazar los datos si es necesario
98
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
99
     * @version 2016-12-10
100
     */
101
    public function setDeclaracion($declaracion)
102
    {
103
        $this->declaracion = $declaracion;
104
    }
105
106
    /**
107
     * Método que agrega los datos del cedente
108
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
109
     * @version 2017-07-24
110
     */
111
    public function setCedente(array $cedente = [])
112
    {
113
        $this->datos['Cesion']['DocumentoCesion']['Cedente'] = \sasco\LibreDTE\Arreglo::mergeRecursiveDistinct([
114
            'RUT' => $this->Encabezado['Emisor']['RUTEmisor'],
115
            'RazonSocial' => $this->Encabezado['Emisor']['RznSoc'],
116
            'Direccion' => $this->Encabezado['Emisor']['DirOrigen'].', '.$this->Encabezado['Emisor']['CmnaOrigen'],
117
            'eMail' => !empty($this->Encabezado['Emisor']['CorreoEmisor']) ? $this->Encabezado['Emisor']['CorreoEmisor'] : false,
118
            'RUTAutorizado' => [
119
                'RUT' => false,
120
                'Nombre' => false,
121
            ],
122
            'DeclaracionJurada' => false,
123
        ], $cedente);
124
        if (!$this->datos['Cesion']['DocumentoCesion']['Cedente']['DeclaracionJurada']) {
125
            $this->datos['Cesion']['DocumentoCesion']['Cedente']['DeclaracionJurada'] = mb_substr(str_replace(
126
                [
127
                    '{usuario_nombre}',
128
                    '{usuario_run}',
129
                    '{emisor_razon_social}',
130
                    '{emisor_rut}',
131
                    '{cesionario_razon_social}',
132
                    '{cesionario_rut}',
133
                    '{receptor_razon_social}',
134
                    '{receptor_rut}',
135
                ],
136
                [
137
                    $this->datos['Cesion']['DocumentoCesion']['Cedente']['RUTAutorizado']['Nombre'],
138
                    $this->datos['Cesion']['DocumentoCesion']['Cedente']['RUTAutorizado']['RUT'],
139
                    $this->datos['Cesion']['DocumentoCesion']['Cedente']['RazonSocial'],
140
                    $this->datos['Cesion']['DocumentoCesion']['Cedente']['RUT'],
141
                    $this->datos['Cesion']['DocumentoCesion']['Cesionario']['RazonSocial'],
142
                    $this->datos['Cesion']['DocumentoCesion']['Cesionario']['RUT'],
143
                    $this->Encabezado['Receptor']['RznSocRecep'],
144
                    $this->Encabezado['Receptor']['RUTRecep'],
145
                ],
146
                $this->declaracion
147
            ), 0, 512);
148
        }
149
    }
150
151
    /**
152
     * Método que agrega los datos del cesionario
153
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
154
     * @version 2016-12-10
155
     */
156
    public function setCesionario(array $cesionario)
157
    {
158
        $this->datos['Cesion']['DocumentoCesion']['Cesionario'] = $cesionario;
159
    }
160
161
    /**
162
     * Método que asigna otros datos de la cesión. Su uso es opcional, ya que de no ser llamado
163
     * se usará el monto total del documento y su fecha de emisión o pago si existe
164
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
165
     * @version 2016-12-10
166
     */
167
    public function setDatos(array $datos)
168
    {
169 View Code Duplication
        if (!empty($datos['MontoCesion'])) {
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...
170
            $this->datos['Cesion']['DocumentoCesion']['MontoCesion'] = $datos['MontoCesion'];
171
        }
172 View Code Duplication
        if (!empty($datos['UltimoVencimiento'])) {
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...
173
            $this->datos['Cesion']['DocumentoCesion']['UltimoVencimiento'] = $datos['UltimoVencimiento'];
174
        }
175 View Code Duplication
        if (!empty($datos['OtrasCondiciones'])) {
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...
176
            $this->datos['Cesion']['DocumentoCesion']['OtrasCondiciones'] = $datos['OtrasCondiciones'];
177
        }
178 View Code Duplication
        if (!empty($datos['eMailDeudor'])) {
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...
179
            $this->datos['Cesion']['DocumentoCesion']['eMailDeudor'] = $datos['eMailDeudor'];
180
        }
181
    }
182
183
    /**
184
     * Método que realiza la firma de cesión
185
     * @param Firma objeto que representa la Firma Electrónca
186
     * @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...
187
     * @author Adonias Vasquez (adonias.vasquez[at]epys.cl)
188
     * @version 2016-08-10
189
     */
190
    public function firmar(\sasco\LibreDTE\FirmaElectronica $Firma)
191
    {
192
        $xml_unsigned = (new \sasco\LibreDTE\XML())->generate($this->datos)->saveXML();
193
        $xml = $Firma->signXML($xml_unsigned, '#LibreDTE_Cesion', 'DocumentoCesion');
0 ignored issues
show
Documentation introduced by
$xml_unsigned 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...
194
        if (!$xml) {
195
            \sasco\LibreDTE\Log::write(
196
                \sasco\LibreDTE\Estado::DTE_ERROR_FIRMA,
197
                \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::DTE_ERROR_FIRMA, '#LibreDTE_Cesion')
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...MA, '#LibreDTE_Cesion') 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...
198
            );
199
            return false;
200
        }
201
        $this->xml = new \sasco\LibreDTE\XML();
0 ignored issues
show
Bug introduced by
The property xml does not exist. Did you maybe forget to declare it?

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
202
        if (!$this->xml->loadXML($xml) or !$this->schemaValidate())
0 ignored issues
show
Bug introduced by
It seems like $xml defined by $Firma->signXML($xml_uns...on', 'DocumentoCesion') on line 193 can also be of type boolean; however, sasco\LibreDTE\XML::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...
203
            return false;
204
        return true;
205
    }
206
207
    /**
208
     * Método que entrega el string con el XML de la cesion
209
     * @author Adonias Vasquez (adonias.vasquez[at]epys.cl)
210
     * @version 2016-08-10
211
     */
212
    public function saveXML()
213
    {
214
        return $this->xml->saveXML();
215
    }
216
217
    /**
218
     * Método que valida el schema de la Cesion
219
     * @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...
220
     * @author Adonias Vasquez (adonias.vasquez[at]epys.cl)
221
     * @version 2016-08-10
222
     */
223
    public function schemaValidate()
224
    {
225
        return true;
226
    }
227
228
    /**
229
     * Método que entrega los datos del cedente
230
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
231
     * @version 2016-12-10
232
     */
233
    public function getCedente()
234
    {
235
        return $this->datos['Cesion']['DocumentoCesion']['Cedente'];
236
    }
237
238
    /**
239
     * Método que entrega los datos del cesionario
240
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
241
     * @version 2016-12-10
242
     */
243
    public function getCesionario()
244
    {
245
        return $this->datos['Cesion']['DocumentoCesion']['Cesionario'];
246
    }
247
248
    /**
249
     * Método que carga un XML y asigna el objeto XML correspondiente
250
     * @return Objeto XML
251
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
252
     * @version 2020-07-27
253
     */
254
    public function loadXML($xml_data)
255
    {
256
        $this->xml = new \sasco\LibreDTE\XML();
257
        if (!$this->xml->loadXML($xml_data)) {
258
            return false;
259
        }
260
        return $this->xml;
261
    }
262
263
}
264