|
3 | 3 |
|
4 | 4 | use Sabre\Xml\Service;
|
5 | 5 | use Saleh7\Zatca\Exceptions\ZatcaStorageException;
|
6 |
| - |
| 6 | +use DOMDocument; |
7 | 7 | /**
|
8 | 8 | * Class GeneratorInvoice
|
9 | 9 | *
|
@@ -40,12 +40,37 @@ public static function invoice(Invoice $invoice, string $currencyId = 'SAR'): se
|
40 | 40 | 'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' => 'ext'
|
41 | 41 | ];
|
42 | 42 |
|
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); |
45 | 48 |
|
46 | 49 | return $instance;
|
47 | 50 | }
|
48 | 51 |
|
| 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 | + } |
49 | 74 | /**
|
50 | 75 | * Saves the generated invoice as an XML file.
|
51 | 76 | *
|
|
0 commit comments