Test Failed
Push — master ( 1f5d45...b072a0 )
by JAIME ELMER
04:15
created

DocumentGenerator::getNamespaceMap()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 21
nc 5
nop 1
dl 0
loc 23
rs 9.2728
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * MÓDULO DE EMISIÓN ELECTRÓNICA F72X
5
 * UBL 2.1
6
 * Version 1.1
7
 * 
8
 * Copyright 2018, Jaime Cruz
9
 */
10
11
namespace F72X\Sunat;
12
13
use InvalidArgumentException;
14
use F72X\Tools\XmlDSig;
15
use F72X\Tools\PdfGenerator;
16
use F72X\Repository;
17
use F72X\Sunat\Catalogo;
18
use F72X\Tools\XmlService;
19
use F72X\Sunat\Document\Factura;
20
use F72X\Sunat\Document\Boleta;
21
use F72X\Sunat\Document\NotaCredito;
22
use F72X\Sunat\Document\NotaDebito;
23
use F72X\Exception\InvalidInputException;
24
25
class DocumentGenerator {
26
27
    /**
28
     * Crear documento electrónico
29
     * 
30
     * Crea Factura, Boleta, Nota de crédito y Nota de débito.
31
     * 
32
     * Procesa la data proporcionada para el tipo de documento indicado
33
     * 
34
     * @param string $shortCode FAC|BOL|NCR|NDE
35
     * @param array $data
36
     * @param string $currencyCode
37
     */
38
    public static function createDocument($shortCode, array $data) {
39
        // Validate type
40
        if (!in_array($shortCode, ['FAC', 'BOL', 'NCR', 'NDE'])) {
41
            throw new InvalidArgumentException("F72X: El tipo '$shortCode', es invalido use FAC|BOL|NCR|NDE");
42
        }
43
        // Set Document Type Code
44
        $docType = Catalogo::getDocumentType($shortCode);
45
        $data['documentType'] = $docType;
46
        // Validate input
47
        self::validateData($data, $shortCode);
48
        // Data map
49
        $dataMap = new DataMap($data, $docType);
50
        // Generate XML
51
        if ($docType == Catalogo::DOCTYPE_FACTURA) {
52
            return new Factura($dataMap);
53
        }
54
        if ($docType == Catalogo::DOCTYPE_BOLETA) {
55
            return new Boleta($dataMap);
56
        }
57
        if ($docType == Catalogo::DOCTYPE_NOTA_CREDITO) {
58
            return new NotaCredito($dataMap);
59
        }
60
        return new NotaDebito($dataMap);
61
    }
62
63
    /**
64
     * 
65
     * @param string $documentType 01|03|07|08
66
     * @param string $affectedDocumentType 01|03
67
     * @param string $baseSeries ###|C##|D##
68
     * @return string F###|B###|FC##|FD#|#BC##|BD##
69
     */
70
    public static function buildDocumentSeries($documentType, $affectedDocumentType, $baseSeries) {
71
        return Catalogo::getDocumentSeriesPrefix($documentType, $affectedDocumentType) . $baseSeries;
72
    }
73
74
    private static function validateData(array $data, $type) {
75
        $validator = new InputValidator($data, $type);
76
        // Input validation
77
        if (!$validator->isValid()) {
78
            throw new InvalidInputException($validator->getErrors());
79
        }
80
    }
81
82
    /**
83
     * 
84
     * @param Factura|Boleta|NotaCredito|NotaDebito $XmlDoc
85
     */
86
    public static function generateFiles($XmlDoc) {
87
        // Save Input
88
        self::saveBillInput($XmlDoc);
89
        // Save Document
90
        self::saveBill($XmlDoc);
91
        // Sign Document
92
        self::singBill($XmlDoc);
93
        // Compress Document
94
        self::zipBill($XmlDoc);
95
        // Generate PDF
96
        self::generatePdf($XmlDoc);
97
    }
98
99
    private static function saveBillInput($XmlDoc) {
100
        $billName = $XmlDoc->getBillName();
101
        Repository::saveBillInput($billName, json_encode($XmlDoc->getDataMap()->getRawData(), JSON_PRETTY_PRINT));
102
    }
103
104
    private static function singBill($XmlDoc) {
105
        $billName = $XmlDoc->getBillName();
106
        XmlDSig::sign($billName);
107
    }
108
109
    private static function zipBill($XmlDoc) {
110
        $billName = $XmlDoc->getBillName();
111
        Repository::zipBill($billName);
112
    }
113
114
    public static function generatePdf($XmlDoc) {
115
        $billName = $XmlDoc->getBillName();
116
        $Invoice = $XmlDoc->getDataMap();
117
        PdfGenerator::generatePdf($Invoice, $billName);
118
    }
119
120
    private static function saveBill($Bill) {
121
        $xmlService = new XmlService('1.0', 'ISO-8859-1');
122
        $documentType = $Bill->getDataMap()->getDocumentType();
123
        // Set namespaces
124
        $xmlService->namespaceMap = self::getNamespaceMap($documentType);
125
        $billName = $Bill->getBillName();
126
        // Xml Root
127
        $xmlRoot = self::getXmlRoot($documentType);
128
        $billContent = $xmlService->write($xmlRoot, $Bill);
129
        Repository::saveBill($billName, $billContent);
130
    }
131
132
    /**
133
     * 
134
     * @param string $documentType 01|03|07|08
135
     * @return string Invoice|CreditNote|DebitNote
136
     */
137
    private static function getXmlRoot($documentType) {
138
        switch ($documentType) {
139
            case Catalogo::DOCTYPE_FACTURA      :
140
            case Catalogo::DOCTYPE_BOLETA       : return 'Invoice';
141
            case Catalogo::DOCTYPE_NOTA_CREDITO : return 'CreditNote';
142
            case Catalogo::DOCTYPE_NOTA_DEBITO  : return 'DebitNote';
143
        }
144
    }
145
 
146
    /**
147
     * 
148
     * @param string $documentType 01|03|07|08
149
     * @return array
150
     */
151
    private static function getNamespaceMap($documentType) {
152
        switch ($documentType) {
153
            case Catalogo::DOCTYPE_FACTURA :
154
            case Catalogo::DOCTYPE_BOLETA :
155
                $topNamespace = 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2';
156
                break;
157
            case Catalogo::DOCTYPE_NOTA_CREDITO :
158
                $topNamespace = 'urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2';
159
                break;
160
            case Catalogo::DOCTYPE_NOTA_DEBITO :
161
                $topNamespace = 'urn:oasis:names:specification:ubl:schema:xsd:DebitNote-2';
162
                break;
163
        }
164
        return [
165
            $topNamespace                                                                 => '',
166
            'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2'    => 'cac',
167
            'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2'        => 'cbc',
168
            'urn:un:unece:uncefact:documentation:2'                                       => 'ccts',
169
            'http://www.w3.org/2000/09/xmldsig#'                                          => 'ds',
170
            'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2'    => 'ext',
171
            'urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2'           => 'qdt',
172
            'urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2' => 'udt',
173
            'http://www.w3.org/2001/XMLSchema-instance'                                   => 'xsi'
174
        ];
175
    }
176
177
}
178