1 | <?php |
||
14 | class Buffer |
||
15 | { |
||
16 | /** |
||
17 | * The result buffer |
||
18 | * |
||
19 | * @var string |
||
20 | */ |
||
21 | protected $result; |
||
22 | |||
23 | |||
24 | /** |
||
25 | * Initialize an empty buffer |
||
26 | */ |
||
27 | 6 | public function __construct() |
|
28 | { |
||
29 | 6 | $this->result = ''; |
|
30 | 6 | $this->indent = 0; |
|
|
|||
31 | 6 | } |
|
32 | |||
33 | |||
34 | /** |
||
35 | * Write some code to the buffer |
||
36 | * |
||
37 | * @param string $data |
||
38 | * @return self |
||
39 | */ |
||
40 | 5 | public function write($data) |
|
41 | { |
||
42 | 5 | return $this->indent()->raw($data); |
|
43 | } |
||
44 | |||
45 | |||
46 | /** |
||
47 | * Write an EOL character |
||
48 | * |
||
49 | * @return self |
||
50 | */ |
||
51 | 3 | public function eol() |
|
52 | { |
||
53 | 3 | $this->result .= PHP_EOL; |
|
54 | 3 | return $this; |
|
55 | } |
||
56 | |||
57 | /** |
||
58 | * Write some data without formatting. |
||
59 | * |
||
60 | * @param string $data |
||
61 | * @return self |
||
62 | */ |
||
63 | 5 | public function raw($data) |
|
64 | { |
||
65 | 5 | $this->result .= $data; |
|
66 | 5 | return $this; |
|
67 | } |
||
68 | |||
69 | |||
70 | /** |
||
71 | * Write a line with indentation and a newline at the end. |
||
72 | * |
||
73 | * @param string $data |
||
74 | * @return self |
||
75 | */ |
||
76 | 3 | public function writeln($data) |
|
77 | { |
||
78 | 3 | return $this->write($data)->eol(); |
|
79 | } |
||
80 | |||
81 | |||
82 | /** |
||
83 | * Adds indentation to the buffer if $increment is not specified. Otherwise increment the current indentation |
||
84 | * $increment steps. You should pass a negative number to outdent. |
||
85 | * |
||
86 | * @param int $increment |
||
87 | * @return Buffer |
||
88 | */ |
||
89 | 6 | public function indent($increment = null) |
|
90 | { |
||
91 | 6 | if (null !== $increment) { |
|
92 | 3 | $this->indent += $increment; |
|
93 | 3 | if ($this->indent < 0) { |
|
94 | 1 | throw new \InvalidArgumentException("Indent can not reach below zero!"); |
|
95 | } |
||
96 | 2 | } else { |
|
97 | 5 | $this->raw(str_repeat(' ', $this->indent)); |
|
98 | } |
||
99 | 5 | return $this; |
|
100 | } |
||
101 | |||
102 | |||
103 | /** |
||
104 | * Return the buffer contents. |
||
105 | * |
||
106 | * @return string |
||
107 | */ |
||
108 | 5 | public function getResult() |
|
109 | { |
||
110 | 5 | return $this->result; |
|
111 | } |
||
112 | |||
113 | |||
114 | /** |
||
115 | * Shorthand method to add the specified variable as it's php representation. |
||
116 | * |
||
117 | * @param mixed $var |
||
118 | * @return Buffer |
||
119 | */ |
||
120 | public function asPhp($var) |
||
124 | } |
||
125 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: