Completed
Push — master ( f7386a...13fee1 )
by Sam
02:48
created

Writer::dump()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 16
rs 9.4285
cc 3
eloc 8
nc 3
nop 0
1
<?php
2
3
namespace Jalle19\HaPHProxy;
4
5
use Jalle19\HaPHProxy\Parameter\Parameter;
6
use Jalle19\HaPHProxy\Section\AbstractSection;
7
use Jalle19\HaPHProxy\Section\NamedSection;
8
9
/**
10
 * Class Writer
11
 * @package Jalle19\HaPHProxy
12
 * @author  Sam Stenvall <[email protected]>
13
 * @license GNU General Public License 2.0+
14
 */
15
class Writer
16
{
17
18
	const DEFAULT_PREFACE = '# Generated with Jalle19/haphproxy';
19
	const DEFAULT_INDENT  = '    ';
20
21
	/**
22
	 * @var Configuration
23
	 */
24
	private $configuration;
25
26
	/**
27
	 * @var string
28
	 */
29
	private $preface = self::DEFAULT_PREFACE;
30
31
	/**
32
	 * @var string
33
	 */
34
	private $indent = self::DEFAULT_INDENT;
35
36
37
	/**
38
	 * Writer constructor.
39
	 *
40
	 * @param Configuration $configuration
41
	 */
42
	public function __construct(Configuration $configuration)
43
	{
44
		$this->configuration = $configuration;
45
	}
46
47
48
	/**
49
	 * @param Configuration $configuration
50
	 */
51
	public function setConfiguration($configuration)
52
	{
53
		$this->configuration = $configuration;
54
	}
55
56
57
	/**
58
	 * @param string $preface
59
	 */
60
	public function setPreface($preface)
61
	{
62
		$this->preface = $preface;
63
	}
64
65
66
	/**
67
	 * @param string $indent
68
	 */
69
	public function setIndent($indent)
70
	{
71
		$this->indent = $indent;
72
	}
73
74
75
	/**
76
	 * @return string the configuration as a string
77
	 */
78
	public function dump()
79
	{
80
		$configuration = $this->preface . PHP_EOL;
81
82
		foreach ($this->configuration->getSections() as $section) {
83
			$configuration .= $this->writeSection($section);
84
85
			foreach ($section->getParameters() as $parameter) {
86
				$configuration .= $this->indent . $this->writeParameter($parameter) . PHP_EOL;
87
			}
88
89
			$configuration .= PHP_EOL;
90
		}
91
92
		return $configuration;
93
	}
94
95
96
	/**
97
	 * @param AbstractSection $section
98
	 *
99
	 * @return string
100
	 */
101
	private function writeSection(AbstractSection $section)
102
	{
103
		$output = $section->getType();
104
105
		if ($section instanceof NamedSection) {
106
			$output .= ' ' . $section->getName();
107
		}
108
109
		$output .= PHP_EOL;
110
111
		return $output;
112
	}
113
114
115
	/**
116
	 * @param Parameter $parameter
117
	 *
118
	 * @return string
119
	 */
120
	private function writeParameter(Parameter $parameter)
121
	{
122
		$value = $parameter->getValue();
123
124
		if ($value === null) {
125
			return $parameter->getName();
126
		}
127
128
		return $parameter->getName() . ' ' . $parameter->getValue();
129
	}
130
131
}
132