Completed
Push — master ( 0352e7...f089db )
by Andreas
02:01
created

XmlBuilder::createElement()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 3
1
<?php
2
3
namespace Larium\Pay;
4
5
use Closure;
6
use XMLWriter;
7
8
/**
9
 * XmlBuilder provides a fluent way to create xml strings.
10
 *
11
 * @author Andreas Kollaros <[email protected]>
12
 */
13
class XmlBuilder
14
{
15
    protected $writer;
16
17
    public function __construct()
18
    {
19
        $this->writer = new XMLWriter();
20
        $this->writer->openMemory();
21
    }
22
23
    public function instruct($version, $encoding = null, $indent = true)
24
    {
25
        $this->writer->startDocument($version, $encoding);
26
        if ($indent) {
27
            $this->writer->setIndent(true);
28
        }
29
    }
30
31
    public function docType($qualifiedName, $publicId = null, $systemId = null)
32
    {
33
        $this->writer->startDTD($qualifiedName, $publicId, $systemId);
34
        $this->writer->endDTD();
35
    }
36
37
    public function build()
38
    {
39
        $args = func_get_args();
40
41
        $args = reset($args);
42
        $name = array_shift($args);
43
        $block_or_string = array_shift($args);
44
        $attributes = array_shift($args);
45
46
        $this->createElement($name, $block_or_string, $attributes);
47
48
        return $this;
49
    }
50
51
    public function __call($name, $args)
52
    {
53
        $args = array_merge([$name], $args);
54
55
        return $this->build($args);
56
    }
57
58
    public function __toString()
59
    {
60
        $this->writer->endDocument();
61
62
        return $this->writer->outputMemory();
63
    }
64
65
    private function createElement($name, $body, array $attributes = null)
66
    {
67
        $this->writer->startElement($name);
68
69
        $this->createAttributes($attributes);
70
71
        if (is_callable($body)) {
72
            $body($this);
73
        } else {
74
            $this->writer->text($body);
75
        }
76
77
        $this->writer->endElement();
78
    }
79
80
    private function createAttributes(array $attributes = null)
81
    {
82
        if ($attributes) {
83
            foreach ($attributes as $key => $value) {
84
                $this->writer->startAttribute($key);
85
                $this->writer->text($value);
86
                $this->writer->endAttribute();
87
            }
88
        }
89
    }
90
}
91