Completed
Pull Request — master (#1)
by Andreas
03:09
created

XmlBuilder::build()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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 1
    public function __construct()
18
    {
19 1
        $this->writer = new XMLWriter();
20 1
        $this->writer->openMemory();
21 1
    }
22
23 1
    public function instruct($version, $encoding = null, $indent = true)
24
    {
25 1
        $this->writer->startDocument($version, $encoding);
26 1
        if ($indent) {
27 1
            $this->writer->setIndent(true);
28 1
        }
29 1
    }
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 1
    public function build()
38
    {
39 1
        $args = func_get_args();
40
41 1
        $args = reset($args);
42 1
        $name = array_shift($args);
43 1
        $block_or_string = array_shift($args);
44 1
        $attributes = array_shift($args);
45
46 1
        $this->createElement($name, $block_or_string, $attributes);
47
48 1
        return $this;
49
    }
50
51 1
    public function __call($name, $args)
52
    {
53 1
        $args = array_merge([$name], $args);
54
55 1
        return $this->build($args);
56
    }
57
58 1
    public function __toString()
59
    {
60 1
        $this->writer->endDocument();
61
62 1
        return $this->writer->outputMemory();
63
    }
64
65 1
    private function createElement($name, $body, array $attributes = null)
66
    {
67 1
        $this->writer->startElement($name);
68
69 1
        $this->createAttributes($attributes);
70
71 1
        if (is_callable($body)) {
72 1
            $body($this);
73 1
        } else {
74 1
            $this->writer->text($body);
75
        }
76
77 1
        $this->writer->endElement();
78 1
    }
79
80 1
    private function createAttributes(array $attributes = null)
81
    {
82 1
        if ($attributes) {
83 1
            foreach ($attributes as $key => $value) {
84 1
                $this->writer->startAttribute($key);
85 1
                $this->writer->text($value);
86 1
                $this->writer->endAttribute();
87 1
            }
88 1
        }
89 1
    }
90
}
91