Passed
Push — master ( fe7ce5...723ccb )
by Esteban De La Fuente
05:52
created

TemplateDataHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 118
Duplicated Lines 0 %

Test Coverage

Coverage 70.1%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 73
c 2
b 0
f 0
dl 0
loc 118
ccs 61
cts 87
cp 0.701
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
B createHandlers() 0 101 4
A __construct() 0 3 1
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 54
    public function __construct(
57
        private EntityComponentInterface $entityComponent
58
    ) {
59 54
    }
60
61
    /**
62
     * Mapa de campos a handlers para los documentos tributarios electrónicos.
63
     *
64
     * @return array
65
     */
66 54
    protected function createHandlers(): array
67
    {
68 54
        return [
69
            // Tipos de documento.
70 54
            'TipoDTE' => $this->entityComponent->getRepository(
71 54
                TipoDocumentoInterface::class
72 54
            ),
73 54
            'TpoDocRef' => 'alias:TipoDTE',
74
            // RUT.
75 54
            'RUTEmisor' => fn (string $rut) => Rut::formatFull($rut),
76 54
            'RUTRecep' => 'alias:RUTEmisor',
77 54
            'RUTSolicita' => 'alias:RUTEmisor',
78 54
            'RUTTrans' => 'alias:RUTEmisor',
79 54
            'RUTChofer' => 'alias:RUTEmisor',
80
            // Comuna.
81 54
            'CdgSIISucur' => fn (string $comuna) =>
82 53
                $this->entityComponent->getRepository(
83 53
                    Comuna::class
84 53
                )->find($comuna)->getDireccionRegional()
85 54
            ,
86 54
            'CiudadOrigen' => fn (string $comuna) =>
87
                $this->entityComponent->getRepository(
88
                    Comuna::class
89
                )->find($comuna)->getCiudad()
90 54
            ,
91 54
            'CiudadRecep' => 'alias:CiudadOrigen',
92
            // Fechas largas.
93 54
            'FchEmis' => fn (string $fecha) => Date::formatSpanish($fecha),
94 54
            'FchRef' => 'alias:FchEmis',
95 54
            'FchVenc' => 'alias:FchEmis',
96
            // Fechas cortas.
97 54
            'PeriodoDesde' => function (string $fecha) {
98 1
                $timestamp = strtotime($fecha);
99 1
                return date('d/m/Y', $timestamp);
100 54
            },
101 54
            'PeriodoHasta' => 'alias:PeriodoDesde',
102 54
            'FchPago' => 'alias:PeriodoDesde',
103
            // Solo año de una fecha.
104 54
            'FchResol' => fn (string $fecha) => explode('-', $fecha, 2)[0],
105
            // Datos de Aduana.
106 54
            '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 54
            },
125 54
            'TotItems' => 'alias:Number',
126
            // Otros datos que se mapean de un código a su glosa usando un
127
            // repositorio.
128 54
            'TipoImp' => $this->entityComponent->getRepository(
129 54
                ImpuestoAdicionalRetencion::class
130 54
            ),
131 54
            'MedioPago' => $this->entityComponent->getRepository(
132 54
                MedioPago::class
133 54
            ),
134 54
            'FmaPago' => $this->entityComponent->getRepository(
135 54
                FormaPago::class
136 54
            ),
137 54
            'Nacionalidad' => $this->entityComponent->getRepository(
138 54
                AduanaPais::class
139 54
            ),
140 54
            'CodPaisRecep' => 'alias:Nacionalidad',
141 54
            'IndTraslado' => $this->entityComponent->getRepository(
142 54
                Traslado::class
143 54
            ),
144 54
            'CodViaTransp' => $this->entityComponent->getRepository(
145 54
                AduanaTransporte::class
146 54
            ),
147
            //  Timbre Electrónico del Documento (TED).
148 54
            'TED' => function (string $timbre) {
149 54
                $pdf417 = new TCPDF2DBarcode($timbre, 'PDF417,,5');
150 54
                $png = $pdf417->getBarcodePngData(1, 1, [0,0,0]);
151 54
                return 'data:image/png;base64,' . base64_encode($png);
152 54
            },
153
            // Montos sin decimales.
154 54
            'Number' => function (int|float|string $num) {
155
                $num = round((float) $num);
156
                return number_format($num, 0, ',', '.');
157 54
            },
158
            // Montos según moneda.
159 54
            '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($num, $moneda->getDecimales(), ',', '.');
167 54
            },
168 54
        ];
169
    }
170
}
171