Passed
Push — master ( 28a195...c54296 )
by Esteban De La Fuente
06:24
created

TemplateDataHandler::createHandlers()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 105
Code Lines 76

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 59
CRAP Score 4.6129

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 76
c 3
b 0
f 0
nc 1
nop 0
dl 0
loc 105
ccs 59
cts 89
cp 0.6629
crap 4.6129
rs 8.5236

How to fix   Long Method   

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
declare(strict_types=1);
4
5
/**
6
 * LibreDTE: Biblioteca PHP (Núcleo).
7
 * Copyright (C) LibreDTE <https://www.libredte.cl>
8
 *
9
 * Este programa es software libre: usted puede redistribuirlo y/o modificarlo
10
 * bajo los términos de la Licencia Pública General Affero de GNU publicada por
11
 * la Fundación para el Software Libre, ya sea la versión 3 de la Licencia, o
12
 * (a su elección) cualquier versión posterior de la misma.
13
 *
14
 * Este programa se distribuye con la esperanza de que sea útil, pero SIN
15
 * GARANTÍA ALGUNA; ni siquiera la garantía implícita MERCANTIL o de APTITUD
16
 * PARA UN PROPÓSITO DETERMINADO. Consulte los detalles de la Licencia Pública
17
 * General Affero de GNU para obtener una información más detallada.
18
 *
19
 * Debería haber recibido una copia de la Licencia Pública General Affero de
20
 * GNU junto a este programa.
21
 *
22
 * En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
23
 */
24
25
namespace libredte\lib\Core\Package\Billing\Component\Document\Service;
26
27
use Derafu\Lib\Core\Helper\Date;
28
use Derafu\Lib\Core\Helper\Rut;
29
use Derafu\Lib\Core\Package\Prime\Component\Entity\Contract\EntityComponentInterface;
30
use Derafu\Lib\Core\Package\Prime\Component\Template\Abstract\AbstractTemplateDataHandler;
31
use Derafu\Lib\Core\Package\Prime\Component\Template\Contract\DataHandlerInterface;
32
use libredte\lib\Core\Package\Billing\Component\Document\Contract\TipoDocumentoInterface;
33
use libredte\lib\Core\Package\Billing\Component\Document\Entity\AduanaMoneda;
34
use libredte\lib\Core\Package\Billing\Component\Document\Entity\AduanaPais;
35
use libredte\lib\Core\Package\Billing\Component\Document\Entity\AduanaTransporte;
36
use libredte\lib\Core\Package\Billing\Component\Document\Entity\Comuna;
37
use libredte\lib\Core\Package\Billing\Component\Document\Entity\FormaPago;
38
use libredte\lib\Core\Package\Billing\Component\Document\Entity\ImpuestoAdicionalRetencion;
39
use libredte\lib\Core\Package\Billing\Component\Document\Entity\MedioPago;
40
use libredte\lib\Core\Package\Billing\Component\Document\Entity\TagXml;
41
use libredte\lib\Core\Package\Billing\Component\Document\Entity\Traslado;
42
use libredte\lib\Core\Package\Billing\Component\Document\Enum\Moneda;
43
use TCPDF2DBarcode;
44
45
/**
46
 * Servicio para traducir los datos de los documentos a su representación para
47
 * ser utilizada en la renderización del documento.
48
 */
49
class TemplateDataHandler extends AbstractTemplateDataHandler implements DataHandlerInterface
50
{
51
    /**
52
     * Constructor del handler.
53
     *
54
     * @param EntityComponentInterface $entityComponent
55
     */
56 55
    public function __construct(
57
        private EntityComponentInterface $entityComponent
58
    ) {
59 55
    }
60
61
    /**
62
     * Mapa de campos a handlers para los documentos tributarios electrónicos.
63
     *
64
     * @return array
65
     */
66 55
    protected function createHandlers(): array
67
    {
68 55
        return [
69
            // Tipos de documento.
70 55
            'TipoDTE' => $this->entityComponent->getRepository(
71 55
                TipoDocumentoInterface::class
72 55
            ),
73 55
            'TpoDocRef' => 'alias:TipoDTE',
74
            // RUT.
75 55
            'RUTEmisor' => fn (string $rut) => Rut::formatFull($rut),
76 55
            'RUTRecep' => 'alias:RUTEmisor',
77 55
            'RUTSolicita' => 'alias:RUTEmisor',
78 55
            'RUTTrans' => 'alias:RUTEmisor',
79 55
            'RUTChofer' => 'alias:RUTEmisor',
80
            // Comuna.
81 55
            'CdgSIISucur' => fn (string $comuna) =>
82 53
                $this->entityComponent->getRepository(
83 53
                    Comuna::class
84 53
                )->find($comuna)->getDireccionRegional()
85 55
            ,
86 55
            'CiudadOrigen' => fn (string $comuna) =>
87
                $this->entityComponent->getRepository(
88
                    Comuna::class
89
                )->find($comuna)->getCiudad()
90 55
            ,
91 55
            'CiudadRecep' => 'alias:CiudadOrigen',
92
            // Fechas largas.
93 55
            'FchEmis' => fn (string $fecha) => Date::formatSpanish($fecha),
94 55
            'FchRef' => 'alias:FchEmis',
95 55
            'FchVenc' => 'alias:FchEmis',
96
            // Fechas cortas.
97 55
            'PeriodoDesde' => function (string $fecha) {
98 1
                $timestamp = strtotime($fecha);
99 1
                return date('d/m/Y', $timestamp);
100 55
            },
101 55
            'PeriodoHasta' => 'alias:PeriodoDesde',
102 55
            'FchPago' => 'alias:PeriodoDesde',
103
            // Solo año de una fecha.
104 55
            'FchResol' => fn (string $fecha) => explode('-', $fecha, 2)[0],
105
            // Datos de Aduana.
106 55
            'Aduana' => function (string $tagXmlAndValue) {
107
                [$tagXml, $value] = explode(':', $tagXmlAndValue);
108
                $xmlTagEntity = $this->entityComponent->getRepository(
109
                    TagXml::class
110
                )->find($tagXml);
111
                $name = $xmlTagEntity->getGlosa();
112
                $entityClass = $xmlTagEntity->getEntity();
113
                if ($entityClass) {
114
                    $description = $this->entityComponent->getRepository(
115
                        $entityClass
116
                    )->find($value)->getGlosa();
117
                } else {
118
                    $description = $this->handle($tagXml, $value);
119
                }
120
                if ($name && !in_array($description, [false, null, ''], true)) {
121
                    return $name . ': ' . $description;
122
                }
123
                return '';
124 55
            },
125 55
            'TotItems' => 'alias:Number',
126
            // Otros datos que se mapean de un código a su glosa usando un
127
            // repositorio.
128 55
            'TipoImp' => $this->entityComponent->getRepository(
129 55
                ImpuestoAdicionalRetencion::class
130 55
            ),
131 55
            'MedioPago' => $this->entityComponent->getRepository(
132 55
                MedioPago::class
133 55
            ),
134 55
            'FmaPago' => $this->entityComponent->getRepository(
135 55
                FormaPago::class
136 55
            ),
137 55
            'Nacionalidad' => $this->entityComponent->getRepository(
138 55
                AduanaPais::class
139 55
            ),
140 55
            'CodPaisRecep' => 'alias:Nacionalidad',
141 55
            'IndTraslado' => $this->entityComponent->getRepository(
142 55
                Traslado::class
143 55
            ),
144 55
            'CodViaTransp' => $this->entityComponent->getRepository(
145 55
                AduanaTransporte::class
146 55
            ),
147
            //  Timbre Electrónico del Documento (TED).
148 55
            'TED' => function (string $timbre) {
149 55
                $pdf417 = new TCPDF2DBarcode($timbre, 'PDF417,,5');
150 55
                $png = $pdf417->getBarcodePngData(1, 1, [0,0,0]);
151 55
                return 'data:image/png;base64,' . base64_encode($png);
152 55
            },
153
            // Montos sin decimales.
154 55
            'Number' => function (int|float|string $num) {
155
                $num = round((float) $num);
156
                return number_format($num, 0, ',', '.');
157 55
            },
158
            // Montos según moneda.
159 55
            'MontoMoneda' => function (string $value) {
160
                [$codigo, $num] = explode(':', $value);
161
                $result = $this->entityComponent->getRepository(
162
                    AduanaMoneda::class
163
                )->findBy(['glosa' => $codigo]);
164
                $moneda = ($result[0] ?? null)->getMoneda() ?? Moneda::XXX;
0 ignored issues
show
Bug introduced by
The method getMoneda() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

164
                $moneda = ($result[0] ?? null)->/** @scrutinizer ignore-call */ getMoneda() ?? Moneda::XXX;

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
165
                $num = round((float) $num, $moneda->getDecimales());
166
                return number_format(
167
                    $num,
168
                    $moneda->getDecimales(),
169
                    $moneda->getSeparadorDecimal(),
170
                    $moneda->getSeparadorMiles(),
171
                );
172 55
            },
173 55
        ];
174
    }
175
}
176