1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Copyright 2014 Krzysztof Magosa |
4
|
|
|
* |
5
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
6
|
|
|
* you may not use this file except in compliance with the License. |
7
|
|
|
* You may obtain a copy of the License at |
8
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
9
|
|
|
* |
10
|
|
|
* Unless required by applicable law or agreed to in writing, software |
11
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
12
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13
|
|
|
* See the License for the specific language governing permissions and |
14
|
|
|
* limitations under the License. |
15
|
|
|
*/ |
16
|
|
|
namespace KM\Saffron; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Simple class to do basic formatting of generated PHP code. |
20
|
|
|
* It's here just for easier debugging of generated code. |
21
|
|
|
* There is no plan to make it full code formatter. |
22
|
|
|
*/ |
23
|
|
|
class Code |
24
|
|
|
{ |
25
|
|
|
protected $code = ''; |
26
|
|
|
protected $tabSize = 4; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $text Line of code |
30
|
|
|
* @return Code |
31
|
|
|
*/ |
32
|
|
|
public function append($text) |
33
|
|
|
{ |
34
|
|
|
$this->code .= $text."\n"; |
35
|
|
|
return $this; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @return string Formatted code |
40
|
|
|
*/ |
41
|
|
|
public function __toString() |
42
|
|
|
{ |
43
|
|
|
$lines = explode("\n", $this->code); |
44
|
|
|
$indent = 0; |
45
|
|
|
|
46
|
|
|
$result = ''; |
47
|
|
|
foreach ($lines as $line) { |
48
|
|
|
$line = trim($line); |
49
|
|
|
|
50
|
|
|
if (preg_match('#{|\($#', $line)) { |
51
|
|
|
$result .= str_repeat(' ', $indent); |
52
|
|
|
$result .= $line."\n"; |
53
|
|
|
$indent += $this->tabSize; |
54
|
|
|
} elseif (preg_match('#(}$|^\);$)#', $line)) { |
55
|
|
|
$indent = max(0, $indent - $this->tabSize); |
56
|
|
|
$indent = max($indent, 0); |
57
|
|
|
$result .= str_repeat(' ', $indent); |
58
|
|
|
$result .= $line."\n"; |
59
|
|
|
} else { |
60
|
|
|
$result .= str_repeat(' ', $indent); |
61
|
|
|
$result .= $line."\n"; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $result; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|