ValidatorWorker   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 96
Duplicated Lines 0 %

Test Coverage

Coverage 83.33%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 33
dl 0
loc 96
ccs 30
cts 36
cp 0.8333
rs 10
c 1
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A validateSignature() 0 9 2
A validateSchema() 0 28 4
A validate() 0 28 4
A __construct() 0 11 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\Worker;
26
27
use Derafu\Backbone\Abstract\AbstractWorker;
28
use Derafu\Backbone\Attribute\Worker;
29
use Derafu\Backbone\Trait\StrategiesAwareTrait;
30
use Derafu\Signature\Contract\SignatureServiceInterface;
31
use Derafu\Xml\Contract\XmlDocumentInterface;
32
use Derafu\Xml\Contract\XmlServiceInterface;
33
use Derafu\Xml\XmlDocument;
34
use libredte\lib\Core\Package\Billing\Component\Document\Contract\DocumentBagInterface;
35
use libredte\lib\Core\Package\Billing\Component\Document\Contract\DocumentBagManagerWorkerInterface;
36
use libredte\lib\Core\Package\Billing\Component\Document\Contract\ValidatorStrategyInterface;
37
use libredte\lib\Core\Package\Billing\Component\Document\Contract\ValidatorWorkerInterface;
38
use libredte\lib\Core\Package\Billing\Component\Document\Exception\ValidatorException;
39
40
/**
41
 * Clase para los validadores de documentos.
42
 */
43
#[Worker(name: 'validator', component: 'document', package: 'billing')]
44
class ValidatorWorker extends AbstractWorker implements ValidatorWorkerInterface
45
{
46
    use StrategiesAwareTrait;
47
48 53
    public function __construct(
49
        private DocumentBagManagerWorkerInterface $documentBagManager,
50
        private XmlServiceInterface $xmlService,
51
        private SignatureServiceInterface $signatureService,
52
        iterable $jobs = [],
53
        iterable $handlers = [],
54
        iterable $strategies = []
55
    ) {
56 53
        $this->setJobs($jobs);
57 53
        $this->setHandlers($handlers);
58 53
        $this->setStrategies($strategies);
59
    }
60
61
    /**
62
     * {@inheritDoc}
63
     */
64 53
    public function validate(
65
        DocumentBagInterface|XmlDocumentInterface|string $source
66
    ): void {
67
        // Asignar la bolsa del DTE a partir de la fuente.
68 53
        if (is_string($source)) {
69
            // Importante: Esto quitará la firma, no sirve para otras
70
            // validaciones (de esquema o firma). Solo para esta validación que
71
            // solo valida los datos contenidos en el documento.
72
            $source = 'parser.strategy.default.xml:' . $source;
73
        }
74 53
        $bag = $source instanceof DocumentBagInterface
75 53
            ? $source
76
            : $this->documentBagManager->create($source)
77 53
        ;
78
79
        // Si no hay tipo de documento no se podrá normalizar.
80 53
        if (!$bag->getTipoDocumento()) {
81
            throw new ValidatorException(
82
                'No es posible validar sin un TipoDocumento en la $bag.'
83
            );
84
        }
85
86
        // Buscar la estrategia para validar el tipo de documento tributario.
87 53
        $strategy = $this->getStrategy($bag->getTipoDocumento()->getAlias());
0 ignored issues
show
Bug introduced by
It seems like $bag->getTipoDocumento()->getAlias() can also be of type null; however, parameter $strategy of libredte\lib\Core\Packag...orWorker::getStrategy() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

87
        $strategy = $this->getStrategy(/** @scrutinizer ignore-type */ $bag->getTipoDocumento()->getAlias());
Loading history...
88 53
        assert($strategy instanceof ValidatorStrategyInterface);
89
90
        // Validar el documento usando la estrategia.
91 53
        $strategy->validate($bag);
92
    }
93
94
    /**
95
     * {@inheritDoc}
96
     */
97 53
    public function validateSchema(
98
        DocumentBagInterface|XmlDocumentInterface|string $source
99
    ): void {
100
        // Obtener el documento XML.
101 53
        if ($source instanceof DocumentBagInterface) {
102 1
            $xmlDocument = $source->getXmlDocument();
103 53
        } elseif ($source instanceof XmlDocumentInterface) {
104
            $xmlDocument = $source;
105
        } else {
106
            // Importante: Hacerlo de esta forma garantiza que no se pierda el
107
            // nodo Signature. Pues se carga el XML completo a XmlDocument.
108 53
            $xmlDocument = new XmlDocument();
109 53
            $xmlDocument->loadXml($source);
110
        }
111
112
        // Crear una bolsa con el documento XML. Con esto se obtendrá en la
113
        // bolsa el tipo de documento asociado al DTE.
114 53
        $bag = $this->documentBagManager->create($xmlDocument, normalizeAll: false);
115
116
        // Las boletas no se validan de manera individual (el DTE). Se validan
117
        // a través del EnvioBOLETA.
118 53
        if ($bag->getTipoDocumento()->esBoleta()) {
119 5
            return;
120
        }
121
122
        // Validar esquema de otros DTE (no boletas).
123 48
        $schema = dirname(__DIR__, 6) . '/resources/schemas/DTE_v10.xsd';
124 48
        $this->xmlService->validate($bag->getXmlDocument(), $schema);
0 ignored issues
show
Bug introduced by
It seems like $bag->getXmlDocument() can also be of type null; however, parameter $xml of Derafu\Xml\Contract\XmlV...orInterface::validate() does only seem to accept Derafu\Xml\Contract\XmlDocumentInterface, maybe add an additional type check? ( Ignorable by Annotation )

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

124
        $this->xmlService->validate(/** @scrutinizer ignore-type */ $bag->getXmlDocument(), $schema);
Loading history...
125
    }
126
127
    /**
128
     * {@inheritDoc}
129
     */
130 53
    public function validateSignature(
131
        DocumentBagInterface|XmlDocumentInterface|string $source
132
    ): void {
133 53
        $xml = $source instanceof DocumentBagInterface
134 1
            ? $source->getXmlDocument()
135 53
            : $source
136 53
        ;
137
138 53
        $this->signatureService->validateXml($xml);
0 ignored issues
show
Bug introduced by
It seems like $xml can also be of type null; however, parameter $xml of Derafu\Signature\Contrac...nterface::validateXml() does only seem to accept Derafu\Xml\Contract\XmlDocumentInterface|string, maybe add an additional type check? ( Ignorable by Annotation )

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

138
        $this->signatureService->validateXml(/** @scrutinizer ignore-type */ $xml);
Loading history...
139
    }
140
}
141