Completed
Push — master ( 1994ca...a6fb77 )
by Andreas
03:32
created

XmlBuilder   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 90.48%

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 0
dl 0
loc 78
ccs 38
cts 42
cp 0.9048
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A docType() 0 5 1
A build() 0 13 1
A __call() 0 6 1
A __toString() 0 6 1
A instruct() 0 7 2
A createElement() 0 14 2
A createAttributes() 0 10 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 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
        }
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
        } 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
            }
88
        }
89 1
    }
90
}
91