xref: /plugin/struct/meta/ConfigParser.php (revision 2be187cdcf79ec0d09aea94af4883e5135a65909)
1<?php
2
3namespace dokuwiki\plugin\struct\meta;
4
5/**
6 * Class ConfigParser
7 *
8 * Utilities to parse the configuration syntax into an array
9 *
10 * @package dokuwiki\plugin\struct\meta
11 */
12class ConfigParser {
13
14    protected $config = array();
15
16    /**
17     * Parser constructor.
18     *
19     * parses the given configuration lines
20     *
21     * @param $lines
22     */
23    public function __construct($lines) {
24        /** @var \helper_plugin_struct_config $helper */
25        $helper = plugin_load('helper', 'struct_config');
26        $this->config = array(
27            'limit' => 0,
28            'dynfilters' => false,
29            'summarize' => false,
30            'rownumbers' => false,
31            'sepbyheaders' => false,
32            'headers' => array(),
33            'widths' => array(),
34            'filter' => array(),
35            'schemas' => array(),
36            'sort' => array()
37        );
38        // parse info
39        foreach($lines as $line) {
40            list($key, $val) = $this->splitLine($line);
41            if(!$key) continue;
42
43            $logic = 'OR';
44            // handle line commands (we allow various aliases here)
45            switch($key) {
46                case 'from':
47                case 'schema':
48                case 'tables':
49                    $this->config['schemas'] = array_merge($this->config['schemas'], $this->parseSchema($val));
50                    break;
51                case 'select':
52                case 'cols':
53                case 'field':
54                case 'col':
55                    $this->config['cols'] = $this->parseValues($val);
56                    break;
57                case 'title':
58                    $this->config['title'] = $val;
59                    break;
60                case 'head':
61                case 'header':
62                case 'headers':
63                    $this->config['headers'] = $this->parseValues($val);
64                    break;
65                case 'align':
66                    $this->config['align'] = $this->parseAlignments($val);
67                    break;
68                case 'width':
69                case 'widths':
70                    $this->config['widths'] = $this->parseWidths($val);
71                    break;
72                case 'min':
73                    $this->config['min'] = abs((int) $val);
74                    break;
75                case 'limit':
76                case 'max':
77                    $this->config['limit'] = abs((int) $val);
78                    break;
79                case 'order':
80                case 'sort':
81                    // FIXME multiple values!?
82                    $this->config['sort'][] = $helper->parseSort($val);
83                    break;
84                case 'where':
85                case 'filter':
86                case 'filterand':
87                    /** @noinspection PhpMissingBreakStatementInspection */
88                case 'and':
89                    $logic = 'AND';
90                case 'filteror':
91                case 'or':
92                    $flt = $helper->parseFilterLine($logic, $val);
93                    if($flt) {
94                        $this->config['filter'][] = $flt;
95                    }
96                    break;
97                case 'page':
98                case 'target':
99                    $this->config['page'] = cleanID($val);
100                    break;
101                case 'dynfilters':
102                    $this->config['dynfilters'] = (bool) $val;
103                    break;
104                case 'rownumbers':
105                    $this->config['rownumbers'] = (bool) $val;
106                    break;
107                case 'summarize':
108                    $this->config['summarize'] = (bool) $val;
109                    break;
110                case 'sepbyheaders':
111                    $this->config['sepbyheaders'] = (bool) $val;
112                    break;
113                default:
114                    throw new StructException("unknown option '%s'", hsc($key));
115            }
116        }
117
118        // fill up headers - a NULL signifies that the column label is wanted
119        $this->config['headers'] = (array) $this->config['headers'];
120        $cnth = count($this->config['headers']);
121        $cntf = count($this->config['cols']);
122        for($i = $cnth; $i < $cntf; $i++) {
123            $this->config['headers'][] = null;
124        }
125    }
126
127    /**
128     * Get the parsed configuration
129     *
130     * @return array
131     */
132    public function getConfig() {
133        return $this->config;
134    }
135
136    /**
137     * Splits the given line into key and value
138     *
139     * @param $line
140     * @return bool|array returns false for empty lines
141     */
142    protected function splitLine($line) {
143        // ignore comments
144        $line = preg_replace('/(?<![&\\\\])#.*$/', '', $line);
145        $line = str_replace('\\#', '#', $line);
146        $line = trim($line);
147        if(empty($line)) return false;
148
149        $line = preg_split('/\s*:\s*/', $line, 2);
150        $line[0] = strtolower($line[0]);
151
152        return $line;
153    }
154
155    /**
156     * parses schema config and aliases
157     *
158     * @param $val
159     * @return array
160     */
161    protected function parseSchema($val) {
162        $schemas = array();
163        $parts = explode(',', $val);
164        foreach($parts as $part) {
165            list($table, $alias) = explode(' ', trim($part));
166            $table = trim($table);
167            $alias = trim($alias);
168            if(!$table) continue;
169
170            $schemas[] = array($table, $alias,);
171        }
172        return $schemas;
173    }
174
175    /**
176     * Parse alignment data
177     *
178     * @param string $val
179     * @return string[]
180     */
181    protected function parseAlignments($val) {
182        $cols = explode(',', $val);
183        $data = array();
184        foreach($cols as $col) {
185            $col = trim(strtolower($col));
186            if($col[0] == 'c') {
187                $align = 'center';
188            } elseif($col[0] == 'r') {
189                $align = 'right';
190            } else {
191                $align = 'left';
192            }
193            $data[] = $align;
194        }
195
196        return $data;
197    }
198
199    /**
200     * Parse width data
201     *
202     * @param $val
203     * @return array
204     */
205    protected function parseWidths($val) {
206        $vals = explode(',', $val);
207        $vals = array_map('trim', $vals);
208        $len = count($vals);
209        for($i = 0; $i < $len; $i++) {
210            $val = trim(strtolower($vals[$i]));
211
212            if(preg_match('/^\d+.?(\d+)?(px|em|ex|ch|rem|%|in|cm|mm|q|pt|pc)$/', $val)) {
213                // proper CSS unit?
214                $vals[$i] = $val;
215            } else if(preg_match('/^\d+$/', $val)) {
216                // decimal only?
217                $vals[$i] = $val . 'px';
218            } else {
219                // invalid
220                $vals[$i] = '';
221            }
222        }
223        return $vals;
224    }
225
226    /**
227     * Split values at the commas,
228     * - Wrap with quotes to escape comma, quotes escaped by two quotes
229     * - Within quotes spaces are stored.
230     *
231     * @param string $line
232     * @return array
233     */
234    protected function parseValues($line) {
235        $values = array();
236        $inQuote = false;
237        $escapedQuote = false;
238        $value = '';
239        $len = strlen($line);
240        for($i = 0; $i < $len; $i++) {
241            if($line{$i} == '"') {
242                if($inQuote) {
243                    if($escapedQuote) {
244                        $value .= '"';
245                        $escapedQuote = false;
246                        continue;
247                    }
248                    if($line{$i + 1} == '"') {
249                        $escapedQuote = true;
250                        continue;
251                    }
252                    array_push($values, $value);
253                    $inQuote = false;
254                    $value = '';
255                    continue;
256                } else {
257                    $inQuote = true;
258                    $value = ''; //don't store stuff before the opening quote
259                    continue;
260                }
261            } else if($line{$i} == ',') {
262                if($inQuote) {
263                    $value .= ',';
264                    continue;
265                } else {
266                    if(strlen($value) < 1) {
267                        continue;
268                    }
269                    array_push($values, trim($value));
270                    $value = '';
271                    continue;
272                }
273            }
274            $value .= $line{$i};
275        }
276        if(strlen($value) > 0) {
277            array_push($values, trim($value));
278        }
279        return $values;
280    }
281
282}
283