Completed
Push — master ( 703d5c...d006d0 )
by Esteban De La Fuente
02:13
created

RegistroCompraVenta::request()   C

Complexity

Conditions 11
Paths 30

Size

Total Lines 48
Code Lines 36

Duplication

Lines 19
Ratio 39.58 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 19
loc 48
rs 5.2653
cc 11
eloc 36
nc 30
nop 3

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 con las acciones asociadas al registro de compras y ventas del SII
28
 * Este registro reemplaza a LibroCompraVenta (IECV)
29
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
30
 * @version 2017-08-28
31
 */
32
class RegistroCompraVenta
33
{
34
35
    public static $dtes = [
36
        33 => 'Factura electrónica',
37
        34 => 'Factura no afecta o exenta electrónica',
38
        43 => 'Liquidación factura electrónica',
39
    ]; ///< Documentos que tienen acuse de recibo
40
41
    public static $acciones = [
42
        'ERM' => 'Otorga recibo de mercaderías o servicios',
43
        'ACD' => 'Acepta contenido del documento',
44
        'RCD' => 'Reclamo al contenido del documento',
45
        'RFP' => 'Reclamo por falta parcial de mercaderías',
46
        'RFT' => 'Reclamo por falta total de mercaderías',
47
    ]; ///< Posibles acciones a que tiene asociadas un DTE
48
49
    private static $wsdl = [
50
        'https://ws1.sii.cl/WSREGISTRORECLAMODTE/registroreclamodteservice?wsdl',
51
        'https://ws2.sii.cl/WSREGISTRORECLAMODTECERT/registroreclamodteservice?wsdl',
52
    ]; ///< Rutas de los WSDL de producción y certificación
53
54
    private $token; ///< Token que se usará en la sesión de consultas al RCV
55
56
    /**
57
     * Constructor, obtiene el token de la sesión y lo guarda
58
     * @param Firma Objeto con la firma electrónica
59
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
60
     * @version 2017-08-28
61
     */
62
    public function __construct(\sasco\LibreDTE\FirmaElectronica $Firma)
63
    {
64
        $this->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...
65
        if (!$this->token) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->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...
66
            throw new \Exception('No fue posible obtener el token para la sesión del RCV');
67
        }
68
    }
69
70
    /**
71
     * Método que ingresa una acción al registro de compr/venta en el SII
72
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
73
     * @version 2017-08-29
74
     */
75 View Code Duplication
    public function ingresarAceptacionReclamoDoc($rut, $dv, $dte, $folio, $accion)
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...
76
    {
77
        // ingresar acción al DTE
78
        $r = $this->request('ingresarAceptacionReclamoDoc', [
0 ignored issues
show
Documentation introduced by
'ingresarAceptacionReclamoDoc' is of type string, but the function expects a object<sasco\LibreDTE\Sii\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('rutEmisor' => $ru...'accionDoc' => $accion) is of type array<string,?,{"rutEmis...":"?","accionDoc":"?"}>, but the function expects a object<sasco\LibreDTE\Sii\Argumentos>.

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...
79
            'rutEmisor' => $rut,
80
            'dvEmisor' => $dv,
81
            'tipoDoc' => $dte,
82
            'folio' => $folio,
83
            'accionDoc' => $accion,
84
        ]);
85
        // si no se pudo recuperar error
86
        if ($r===false) {
87
            return false;
88
        }
89
        // entregar resultado del ingreso
90
        return [
91
            'codigo' => $r->codResp,
92
            'glosa' => $r->descResp,
93
        ];
94
    }
95
96
    /**
97
     * Método que entrega los eventos asociados a un DTE
98
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
99
     * @version 2017-08-28
100
     */
101
    public function listarEventosHistDoc($rut, $dv, $dte, $folio)
102
    {
103
        // consultar eventos del DTE
104
        $r = $this->request('listarEventosHistDoc', [
0 ignored issues
show
Documentation introduced by
'listarEventosHistDoc' is of type string, but the function expects a object<sasco\LibreDTE\Sii\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('rutEmisor' => $ru...dte, 'folio' => $folio) is of type array<string,?,{"rutEmis...oDoc":"?","folio":"?"}>, but the function expects a object<sasco\LibreDTE\Sii\Argumentos>.

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...
105
            'rutEmisor' => $rut,
106
            'dvEmisor' => $dv,
107
            'tipoDoc' => $dte,
108
            'folio' => $folio,
109
        ]);
110
        // si no se pudo recuperar error
111
        if ($r===false) {
112
            return false;
113
        }
114
        // si hubo error informar
115
        if (!in_array($r->codResp, [8, 15, 16])) {
116
            throw new \Exception($r->descResp);
117
        }
118
        // entregar eventos del DTE
119
        $eventos = [];
120
        if (!empty($r->listaEventosDoc)) {
121
            if (!is_array($r->listaEventosDoc)) {
122
                $r->listaEventosDoc = [$r->listaEventosDoc];
123
            }
124
            foreach ($r->listaEventosDoc as $evento) {
125
                $eventos[] = [
126
                    'codigo' => $evento->codEvento,
127
                    'glosa' => $evento->descEvento,
128
                    'responsable' => $evento->rutResponsable.'-'.$evento->dvResponsable,
129
                    'fecha' => $evento->fechaEvento,
130
                ];
131
            }
132
        }
133
        return $eventos;
134
    }
135
136
    /**
137
     * Entrega información de cesión para el DTE, si es posible o no cederlo
138
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
139
     * @version 2017-08-28
140
     */
141 View Code Duplication
    public function consultarDocDteCedible($rut, $dv, $dte, $folio)
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...
142
    {
143
        // consultar eventos del DTE
144
        $r = $this->request('consultarDocDteCedible', [
0 ignored issues
show
Documentation introduced by
'consultarDocDteCedible' is of type string, but the function expects a object<sasco\LibreDTE\Sii\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('rutEmisor' => $ru...dte, 'folio' => $folio) is of type array<string,?,{"rutEmis...oDoc":"?","folio":"?"}>, but the function expects a object<sasco\LibreDTE\Sii\Argumentos>.

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...
145
            'rutEmisor' => $rut,
146
            'dvEmisor' => $dv,
147
            'tipoDoc' => $dte,
148
            'folio' => $folio,
149
        ]);
150
        // si no se pudo recuperar error
151
        if ($r===false) {
152
            return false;
153
        }
154
        // entregar información de cesión para el DTE
155
        return [
156
            'codigo' => $r->codResp,
157
            'glosa' => $r->descResp,
158
        ];
159
    }
160
161
    /**
162
     *
163
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
164
     * @version 2017-08-29
165
     */
166
    public function consultarFechaRecepcionSii($rut, $dv, $dte, $folio)
167
    {
168
        // consultar eventos del DTE
169
        $r = $this->request('consultarFechaRecepcionSii', [
0 ignored issues
show
Documentation introduced by
'consultarFechaRecepcionSii' is of type string, but the function expects a object<sasco\LibreDTE\Sii\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('rutEmisor' => $ru...dte, 'folio' => $folio) is of type array<string,?,{"rutEmis...oDoc":"?","folio":"?"}>, but the function expects a object<sasco\LibreDTE\Sii\Argumentos>.

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...
170
            'rutEmisor' => $rut,
171
            'dvEmisor' => $dv,
172
            'tipoDoc' => $dte,
173
            'folio' => $folio,
174
        ]);
175
        // si no se pudo recuperar error
176
        if ($r===false) {
177
            return false;
178
        }
179
        // armar y entregar fecha
180
        list($dia, $hora) = explode(' ', $r);
181
        list($d, $m, $Y) = explode('-', $dia);
182
        return $Y.'-'.$m.'-'.$d.' '.$hora;
183
    }
184
185
    /**
186
     * Método para realizar una solicitud al servicio web del SII
187
     * @param request Nombre de la función que se ejecutará en el servicio web
188
     * @param args Argumentos que se pasarán al servicio web
189
     * @param retry Intentos que se realizarán como máximo para obtener respuesta
190
     * @return Objeto o String con la respuesta (depende servicio web)
191
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
192
     * @version 2017-08-28
193
     */
194
    private function request($request, $args, $retry = 10)
195
    {
196 View Code Duplication
        if (!\sasco\LibreDTE\Sii::getVerificarSSL()) {
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...
197
            if (\sasco\LibreDTE\Sii::getAmbiente()==\sasco\LibreDTE\Sii::PRODUCCION) {
198
                $msg = \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::ENVIO_SSL_SIN_VERIFICAR);
199
                \sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::ENVIO_SSL_SIN_VERIFICAR, $msg, LOG_WARNING);
0 ignored issues
show
Documentation introduced by
$msg 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...
Documentation introduced by
LOG_WARNING is of type integer, but the function expects a object<sasco\LibreDTE\Gravedad>.

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...
200
            }
201
            $options = ['stream_context' => stream_context_create([
202
                'ssl' => [
203
                    'verify_peer' => false,
204
                    'verify_peer_name' => false,
205
                    'allow_self_signed' => true
206
                ]
207
            ])];
208
        } else {
209
            $options = [];
210
        }
211
        try {
212
            $wsdl = self::$wsdl[\sasco\LibreDTE\Sii::getAmbiente()];
213
            $soap = new \SoapClient($wsdl, $options);
214
            $soap->__setCookie('TOKEN', $this->token);
215
        } catch (\Exception $e) {
216
            $msg = $e->getMessage();
217
            if (isset($e->getTrace()[0]['args'][1]) and is_string($e->getTrace()[0]['args'][1])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

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

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

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

Let’s take a look at a few examples:

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

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


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

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

Logical Operators are used for Control-Flow

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

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

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

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

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

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

Loading history...
218
                $msg .= ': '.$e->getTrace()[0]['args'][1];
219
            }
220
            \sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, $msg));
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...QUEST_ERROR_SOAP, $msg) 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...
221
            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\RegistroCompraVenta::request of type sasco\LibreDTE\Sii\objeto.

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...
222
        }
223
        for ($i=0; $i<$retry; $i++) {
224
            try {
225
                $body = call_user_func_array([$soap, $request], $args);
226
                break;
227
            } catch (\Exception $e) {
228
                $msg = $e->getMessage();
229
                if (isset($e->getTrace()[0]['args'][1]) and is_string($e->getTrace()[0]['args'][1])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

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

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

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

Let’s take a look at a few examples:

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

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


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

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

Logical Operators are used for Control-Flow

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

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

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

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

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

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

Loading history...
230
                    $msg .= ': '.$e->getTrace()[0]['args'][1];
231
                }
232
                \sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::REQUEST_ERROR_SOAP, $msg));
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...QUEST_ERROR_SOAP, $msg) is of type integer|string, but the function expects a object<sasco\LibreDTE\Mensaje>|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
233
                $body = null;
234
            }
235
        }
236 View Code Duplication
        if ($body===null) {
0 ignored issues
show
Bug introduced by
The variable $body 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...
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...
237
            \sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::REQUEST_ERROR_BODY, \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::REQUEST_ERROR_BODY, $wsdl, $retry));
0 ignored issues
show
Documentation introduced by
\sasco\LibreDTE\Estado::...OR_BODY, $wsdl, $retry) 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...
238
            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\RegistroCompraVenta::request of type sasco\LibreDTE\Sii\objeto.

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...
239
        }
240
        return $body;
241
    }
242
243
}
244