Skip to content

Commit 429fd59

Browse files
committed
feat: Add XML formatting to GeneratorInvoice for improved readability and structured output
1 parent dd56b89 commit 429fd59

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

src/GeneratorInvoice.php

+28-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
use Sabre\Xml\Service;
55
use Saleh7\Zatca\Exceptions\ZatcaStorageException;
6-
6+
use DOMDocument;
77
/**
88
* Class GeneratorInvoice
99
*
@@ -40,12 +40,37 @@ public static function invoice(Invoice $invoice, string $currencyId = 'SAR'): se
4040
'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' => 'ext'
4141
];
4242

43-
// Store generated XML inside the instance
44-
$instance->generatedXml = $xmlService->write('Invoice', [$invoice]);
43+
// Serialize the invoice object to XML.
44+
$rawXml = $xmlService->write('Invoice', [$invoice]);
45+
46+
// Format the XML using the dedicated formatting function.
47+
$instance->generatedXml = self::formatXml($rawXml);
4548

4649
return $instance;
4750
}
4851

52+
/**
53+
* Format XML with proper indentation and convert 2-space indentation to 4-space indentation.
54+
*
55+
* @param string $xml Unformatted XML string.
56+
* @return string Formatted XML string.
57+
*/
58+
private static function formatXml(string $xml): string
59+
{
60+
$dom = new DOMDocument('1.0', 'UTF-8');
61+
$dom->preserveWhiteSpace = false;
62+
$dom->formatOutput = true;
63+
$dom->loadXML($xml);
64+
$dom->encoding = 'UTF-8';
65+
$formattedXml = $dom->saveXML();
66+
67+
// Convert 2-space indentation to 4-space indentation.
68+
$formattedXml = preg_replace_callback('/^([ ]+)/m', function ($matches) {
69+
return str_repeat(' ', strlen($matches[1]) / 2);
70+
}, $formattedXml);
71+
72+
return $formattedXml;
73+
}
4974
/**
5075
* Saves the generated invoice as an XML file.
5176
*

0 commit comments

Comments
 (0)