This repository has been archived by the owner on Jan 29, 2020. It is now read-only.
/
Xml.php
97 lines (86 loc) · 2.76 KB
/
Xml.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Config
*/
namespace Zend\Config\Writer;
use XMLWriter;
use Zend\Config\Exception;
/**
* @category Zend
* @package Zend_Config
* @subpackage Writer
*/
class Xml extends AbstractWriter
{
/**
* processConfig(): defined by AbstractWriter.
*
* @param array $config
* @return string
*/
public function processConfig(array $config)
{
$writer = new XMLWriter('UTF-8');
$writer->openMemory();
$writer->setIndent(true);
$writer->setIndentString(str_repeat(' ', 4));
$writer->startDocument('1.0', 'UTF-8');
$writer->startElement('zend-config');
foreach ($config as $sectionName => $data) {
if (!is_array($data)) {
$writer->writeElement($sectionName, (string) $data);
} else {
$this->addBranch($sectionName, $data, $writer);
}
}
$writer->endElement();
$writer->endDocument();
return $writer->outputMemory();
}
/**
* Add a branch to an XML object recursively.
*
* @param string $branchName
* @param array $config
* @param XMLWriter $writer
* @return void
* @throws Exception\RuntimeException
*/
protected function addBranch($branchName, array $config, XMLWriter $writer)
{
$branchType = null;
foreach ($config as $key => $value) {
if ($branchType === null) {
if (is_numeric($key)) {
$branchType = 'numeric';
} else {
$writer->startElement($branchName);
$branchType = 'string';
}
} elseif ($branchType !== (is_numeric($key) ? 'numeric' : 'string')) {
throw new Exception\RuntimeException('Mixing of string and numeric keys is not allowed');
}
if ($branchType === 'numeric') {
if (is_array($value)) {
$this->addBranch($value, $value, $writer);
} else {
$writer->writeElement($branchName, (string) $value);
}
} else {
if (is_array($value)) {
$this->addBranch($key, $value, $writer);
} else {
$writer->writeElement($key, (string) $value);
}
}
}
if ($branchType === 'string') {
$writer->endElement();
}
}
}