Completed
Push — master ( 362734...2f4f06 )
by Esteban De La Fuente
01:42
created

Formatos::getFormatos()   B

Complexity

Conditions 7
Paths 2

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.6346
c 0
b 0
f 0
cc 7
nc 2
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\Dte;
25
26
/**
27
 * Clase para convertir entre formatos soportados oficialmente por LibreDTE para
28
 * los DTE
29
 * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
30
 * @version 2020-03-13
31
 */
32
class Formatos
33
{
34
35
    private static $namespaces = [
36
        '\sasco\LibreDTE',
37
        '\sasco\LibreDTE\Extra'
38
    ]; ///< Posible ubicaciones para los formatos que LibreDTE soporta
39
    private static $formatos = []; ///< Formatos oficialmente soportados (para los que existe un parser)
40
41
    /**
42
     * Método que convierte los datos en el formato de entrada a un arreglo PHP
43
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
44
     * @version 2020-03-13
45
     */
46
    public static function toArray($formato, $datos)
47
    {
48
        $founded = false;
49
        foreach (self::$namespaces as $namespace) {
50
            $formato = str_replace('.', '\\', $formato);
51
            $combinations = [
52
                $namespace.'\Sii\Dte\Formatos\\'.$formato,
53
                $namespace.'\Sii\Dte\Formatos\\'.strtoupper($formato),
54
                $namespace.'\Sii\Dte\Formatos\\'.strtolower($formato),
55
            ];
56
            foreach ($combinations as $class) {
57
                if (class_exists($class)) {
58
                    $founded = $class;
59
                    break;
60
                }
61
            }
62
            if ($founded) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $founded of type string|false is loosely compared to true; 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...
63
                break;
64
            }
65
        }
66
        if (!$founded) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $founded of type string|false 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...
67
            throw new \Exception('Formato '.$formato.' no es válido como entrada para datos del DTE');
68
        }
69
        return $founded::toArray($datos);
70
    }
71
72
    /**
73
     * Método que convierte los datos en el formato de entrada al formato
74
     * oficial en JSON
75
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
76
     * @version 2018-01-19
77
     */
78
    public static function toJSON($formato, $datos)
79
    {
80
        return json_encode(self::toArray($formato, $datos), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
81
    }
82
83
    /**
84
     * Método que obtiene el listado de formatos soportados (para los que existe
85
     * un parser)
86
     * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
87
     * @version 2016-09-12
88
     */
89
    public static function getFormatos()
90
    {
91
        if (!self::$formatos) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::$formatos 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...
92
            $dir = dirname(__FILE__).'/Formatos';
93
            $formatos = scandir($dir);
94
            foreach($formatos as &$formato) {
95
                if ($formato[0]=='.')
96
                    continue;
97
                if (is_dir($dir.'/'.$formato)) {
98
                    $subformatos = scandir($dir.'/'.$formato);
99
                    foreach($subformatos as &$subformato) {
100
                        if ($subformato[0]=='.')
101
                            continue;
102
                        self::$formatos[] = $formato.'.'.substr($subformato, 0, -4);
103
                    }
104
                } else {
105
                    self::$formatos[] = substr($formato, 0, -4);
106
                }
107
            }
108
        }
109
        return self::$formatos;
110
    }
111
112
}
113