Completed
Push — master ( f4bdff...fef961 )
by Thomas
01:46
created

DefaultFormatter::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
namespace gossi\formatter\formatters;
3
4
use gossi\formatter\entities\Group;
5
use phootwork\collection\Queue;
6
use phootwork\tokenizer\Token;
7
8
class DefaultFormatter extends BaseFormatter {
9
10
	private $preCommands;
11
	private $postCommands;
12
	private $showToken = true;
13
14
	protected function init() {
15
		$this->preCommands = new Queue();
16
		$this->postCommands = new Queue();
17
	}
18
19
	public function addPreWrite($content = '') {
20
		$this->preCommands->enqueue(['write', $content]);
21
	}
22
23
	public function addPreWriteln($content = '') {
24
		$this->preCommands->enqueue(['writeln', $content]);
25
	}
26
27
	public function addPreIndent() {
28
		$this->preCommands->enqueue(['indent']);
29
	}
30
31
	public function addPreOutdent() {
32
		$this->preCommands->enqueue(['outdent']);
33
	}
34
35
	public function addPostWrite($content = '') {
36
		$this->postCommands->enqueue(['write', $content]);
37
	}
38
39
	public function addPostWriteln($content = '') {
40
		$this->postCommands->enqueue(['writeln', $content]);
41
	}
42
43
	public function addPostIndent() {
44
		$this->postCommands->enqueue(['indent']);
45
	}
46
47
	public function addPostOutdent() {
48
		$this->postCommands->enqueue(['outdent']);
49
	}
50
51
	public function hideToken() {
52
		$this->showToken = false;
53
	}
54
55
	protected function doVisitToken(Token $token) {
56
		$group = $this->context->getGroupContext();
57
58
		// pre commands
59
		$this->processCommands($this->preCommands);
60
61
		// finish line on semicolon
62
		if ($token->contents == ';' && $group->type != Group::BLOCK) {
63
			$this->context->resetLineContext();
64
			$this->writer->writeln($token->contents);
65
		}
66
67
		// when no semicolon and token output allowed
68
		else if ($this->showToken) {
69
			$this->writer->write($token->contents);
70
		}
71
72
		// post commands
73
		$this->processCommands($this->postCommands);
74
75
		// reset
76
		$this->preCommands->clear();
77
		$this->postCommands->clear();
78
		$this->showToken = true;
79
	}
80
81
	private function processCommands(Queue $commands) {
82
		foreach ($commands as $cmd) {
83
			switch ($cmd[0]) {
84
				case 'write':
85
					$this->writer->write($cmd[1]);
86
					break;
87
88
				case 'writeln':
89
					$this->writer->writeln($cmd[1]);
90
					break;
91
92
				case 'indent':
93
					$this->writer->indent();
94
					break;
95
96
				case 'outdent':
97
					$this->writer->outdent();
98
					break;
99
			}
100
		}
101
	}
102
103
}
104