[SPIP] ~maj v3.0.14-->v3.0.17
[ptitvelo/web/www.git] / www / plugins-dist / textwheel / lib / yaml / sfYamlParser.php
1 <?php
2
3 /*
4 * This file is part of the symfony package.
5 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11 if (!defined('_ECRIRE_INC_VERSION')) return;
12
13 require_once(dirname(__FILE__).'/sfYamlInline.php');
14
15 /**
16 * sfYamlParser parses YAML strings to convert them to PHP arrays.
17 *
18 * @package symfony
19 * @subpackage yaml
20 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
21 * @version SVN: $Id: sfYamlParser.class.php 10832 2008-08-13 07:46:08Z fabien $
22 */
23 class sfYamlParser
24 {
25 protected
26 $value = '',
27 $offset = 0,
28 $lines = array(),
29 $currentLineNb = -1,
30 $currentLine = '',
31 $refs = array();
32
33 /**
34 * Constructor
35 *
36 * @param integer $offset The offset of YAML document (used for line numbers in error messages)
37 */
38 public function __construct($offset = 0)
39 {
40 $this->offset = $offset;
41 }
42
43 /**
44 * Parses a YAML string to a PHP value.
45 *
46 * @param string $value A YAML string
47 *
48 * @return mixed A PHP value
49 *
50 * @throws InvalidArgumentException If the YAML is not valid
51 */
52 public function parse($value)
53 {
54 $this->value = $this->cleanup($value);
55 $this->currentLineNb = -1;
56 $this->currentLine = '';
57 $this->lines = explode("\n", $this->value);
58
59 $data = array();
60 while ($this->moveToNextLine())
61 {
62 if ($this->isCurrentLineEmpty())
63 {
64 continue;
65 }
66
67 // tab?
68 if (preg_match('#^\t+#', $this->currentLine))
69 {
70 throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine));
71 }
72
73 $isRef = $isInPlace = $isProcessed = false;
74 if (preg_match('#^\-(\s+(?P<value>.+?))?\s*$#', $this->currentLine, $values))
75 {
76 if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#', $values['value'], $matches))
77 {
78 $isRef = $matches['ref'];
79 $values['value'] = $matches['value'];
80 }
81
82 // array
83 if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#'))
84 {
85 $c = $this->getRealCurrentLineNb() + 1;
86 $parser = new sfYamlParser($c);
87 $parser->refs =& $this->refs;
88 $data[] = $parser->parse($this->getNextEmbedBlock());
89 }
90 else
91 {
92 if (preg_match('/^([^ ]+)\: +({.*?)$/', $values['value'], $matches))
93 {
94 $data[] = array($matches[1] => sfYamlInline::load($matches[2]));
95 }
96 else
97 {
98 $data[] = $this->parseValue($values['value']);
99 }
100 }
101 }
102 else if (preg_match('#^(?P<key>[^ ].*?) *\:(\s+(?P<value>.+?))?\s*$#', $this->currentLine, $values))
103 {
104 $key = sfYamlInline::parseScalar($values['key']);
105
106 if ('<<' === $key)
107 {
108 if (isset($values['value']) && '*' === substr($values['value'], 0, 1))
109 {
110 $isInPlace = substr($values['value'], 1);
111 if (!array_key_exists($isInPlace, $this->refs))
112 {
113 throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine));
114 }
115 }
116 else
117 {
118 if (isset($values['value']) && $values['value'] !== '')
119 {
120 $value = $values['value'];
121 }
122 else
123 {
124 $value = $this->getNextEmbedBlock();
125 }
126 $c = $this->getRealCurrentLineNb() + 1;
127 $parser = new sfYamlParser($c);
128 $parser->refs =& $this->refs;
129 $parsed = $parser->parse($value);
130
131 $merged = array();
132 if (!is_array($parsed))
133 {
134 throw new InvalidArgumentException(sprintf("YAML merge keys used with a scalar value instead of an array at line %s (%s)", $this->getRealCurrentLineNb() + 1, $this->currentLine));
135 }
136 else if (isset($parsed[0]))
137 {
138 // Numeric array, merge individual elements
139 foreach (array_reverse($parsed) as $parsedItem)
140 {
141 if (!is_array($parsedItem))
142 {
143 throw new InvalidArgumentException(sprintf("Merge items must be arrays at line %s (%s).", $this->getRealCurrentLineNb() + 1, $parsedItem));
144 }
145 $merged = array_merge($parsedItem, $merged);
146 }
147 }
148 else
149 {
150 // Associative array, merge
151 $merged = array_merge($merge, $parsed);
152 }
153
154 $isProcessed = $merged;
155 }
156 }
157 else if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#', $values['value'], $matches))
158 {
159 $isRef = $matches['ref'];
160 $values['value'] = $matches['value'];
161 }
162
163 if ($isProcessed)
164 {
165 // Merge keys
166 $data = $isProcessed;
167 }
168 // hash
169 else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#'))
170 {
171 // if next line is less indented or equal, then it means that the current value is null
172 if ($this->isNextLineIndented())
173 {
174 $data[$key] = null;
175 }
176 else
177 {
178 $c = $this->getRealCurrentLineNb() + 1;
179 $parser = new sfYamlParser($c);
180 $parser->refs =& $this->refs;
181 $data[$key] = $parser->parse($this->getNextEmbedBlock());
182 }
183 }
184 else
185 {
186 if ($isInPlace)
187 {
188 $data = $this->refs[$isInPlace];
189 }
190 else
191 {
192 $data[$key] = $this->parseValue($values['value']);
193 }
194 }
195 }
196 else
197 {
198 // one liner?
199 if (1 == count(explode("\n", rtrim($this->value, "\n"))))
200 {
201 $value = sfYamlInline::load($this->lines[0]);
202 if (is_array($value))
203 {
204 $first = reset($value);
205 if ('*' === substr($first, 0, 1))
206 {
207 $data = array();
208 foreach ($value as $alias)
209 {
210 $data[] = $this->refs[substr($alias, 1)];
211 }
212 $value = $data;
213 }
214 }
215
216 return $value;
217 }
218
219 throw new InvalidArgumentException(sprintf('Unable to parse line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine));
220 }
221
222 if ($isRef)
223 {
224 $this->refs[$isRef] = end($data);
225 }
226 }
227
228 return empty($data) ? null : $data;
229 }
230
231 /**
232 * Returns the current line number (takes the offset into account).
233 *
234 * @return integer The current line number
235 */
236 protected function getRealCurrentLineNb()
237 {
238 return $this->currentLineNb + $this->offset;
239 }
240
241 /**
242 * Returns the current line indentation.
243 *
244 * @return integer The current line indentation
245 */
246 protected function getCurrentLineIndentation()
247 {
248 return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
249 }
250
251 /**
252 * Returns the next embed block of YAML.
253 *
254 * @return string A YAML string
255 */
256 protected function getNextEmbedBlock()
257 {
258 $this->moveToNextLine();
259
260 $newIndent = $this->getCurrentLineIndentation();
261
262 if (!$this->isCurrentLineEmpty() && 0 == $newIndent)
263 {
264 throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
265 }
266
267 $data = array(substr($this->currentLine, $newIndent));
268
269 while ($this->moveToNextLine())
270 {
271 if ($this->isCurrentLineEmpty())
272 {
273 if ($this->isCurrentLineBlank())
274 {
275 $data[] = substr($this->currentLine, $newIndent);
276 }
277
278 continue;
279 }
280
281 $indent = $this->getCurrentLineIndentation();
282
283 if (preg_match('#^(?P<text> *)$#', $this->currentLine, $match))
284 {
285 // empty line
286 $data[] = $match['text'];
287 }
288 else if ($indent >= $newIndent)
289 {
290 $data[] = substr($this->currentLine, $newIndent);
291 }
292 else if (0 == $indent)
293 {
294 $this->moveToPreviousLine();
295
296 break;
297 }
298 else
299 {
300 throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
301 }
302 }
303
304 return implode("\n", $data);
305 }
306
307 /**
308 * Moves the parser to the next line.
309 */
310 protected function moveToNextLine()
311 {
312 if ($this->currentLineNb >= count($this->lines) - 1)
313 {
314 return false;
315 }
316
317 $this->currentLine = $this->lines[++$this->currentLineNb];
318
319 return true;
320 }
321
322 /**
323 * Moves the parser to the previous line.
324 */
325 protected function moveToPreviousLine()
326 {
327 $this->currentLine = $this->lines[--$this->currentLineNb];
328 }
329
330 /**
331 * Parses a YAML value.
332 *
333 * @param string $value A YAML value
334 *
335 * @return mixed A PHP value
336 */
337 protected function parseValue($value)
338 {
339 if ('*' === substr($value, 0, 1))
340 {
341 if (false !== $pos = strpos($value, '#'))
342 {
343 $value = substr($value, 1, $pos - 2);
344 }
345 else
346 {
347 $value = substr($value, 1);
348 }
349
350 if (!array_key_exists($value, $this->refs))
351 {
352 throw new InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine));
353 }
354 return $this->refs[$value];
355 }
356
357 if (preg_match('/^(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?$/', $value, $matches))
358 {
359 $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
360
361 return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers)));
362 }
363 else
364 {
365 return sfYamlInline::load($value);
366 }
367 }
368
369 /**
370 * Parses a folded scalar.
371 *
372 * @param string $separator The separator that was used to begin this folded scalar (| or >)
373 * @param string $indicator The indicator that was used to begin this folded scalar (+ or -)
374 * @param integer $indentation The indentation that was used to begin this folded scalar
375 *
376 * @return string The text value
377 */
378 protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0)
379 {
380 $separator = '|' == $separator ? "\n" : ' ';
381 $text = '';
382
383 $notEOF = $this->moveToNextLine();
384
385 while ($notEOF && $this->isCurrentLineBlank())
386 {
387 $text .= "\n";
388
389 $notEOF = $this->moveToNextLine();
390 }
391
392 if (!$notEOF)
393 {
394 return '';
395 }
396
397 if (!preg_match('#^(?P<indent>'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P<text>.*)$#', $this->currentLine, $matches))
398 {
399 $this->moveToPreviousLine();
400
401 return '';
402 }
403
404 $textIndent = $matches['indent'];
405 $previousIndent = 0;
406
407 $text .= $matches['text'].$separator;
408 while ($this->currentLineNb + 1 < count($this->lines))
409 {
410 $this->moveToNextLine();
411
412 if (preg_match('#^(?P<indent> {'.strlen($textIndent).',})(?P<text>.+)$#', $this->currentLine, $matches))
413 {
414 if (' ' == $separator && $previousIndent != $matches['indent'])
415 {
416 $text = substr($text, 0, -1)."\n";
417 }
418 $previousIndent = $matches['indent'];
419
420 $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator);
421 }
422 else if (preg_match('#^(?P<text> *)$#', $this->currentLine, $matches))
423 {
424 $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n";
425 }
426 else
427 {
428 $this->moveToPreviousLine();
429
430 break;
431 }
432 }
433
434 if (' ' == $separator)
435 {
436 // replace last separator by a newline
437 $text = preg_replace('/ (\n*)$/', "\n$1", $text);
438 }
439
440 switch ($indicator)
441 {
442 case '':
443 $text = preg_replace('#\n+$#s', "\n", $text);
444 break;
445 case '+':
446 break;
447 case '-':
448 $text = preg_replace('#\n+$#s', '', $text);
449 break;
450 }
451
452 return $text;
453 }
454
455 /**
456 * Returns true if the next line is indented.
457 *
458 * @return Boolean Returns true if the next line is indented, false otherwise
459 */
460 protected function isNextLineIndented()
461 {
462 $currentIndentation = $this->getCurrentLineIndentation();
463 $notEOF = $this->moveToNextLine();
464
465 while ($notEOF && $this->isCurrentLineEmpty())
466 {
467 $notEOF = $this->moveToNextLine();
468 }
469
470 if (false === $notEOF)
471 {
472 return false;
473 }
474
475 $ret = false;
476 if ($this->getCurrentLineIndentation() <= $currentIndentation)
477 {
478 $ret = true;
479 }
480
481 $this->moveToPreviousLine();
482
483 return $ret;
484 }
485
486 /**
487 * Returns true if the current line is blank or if it is a comment line.
488 *
489 * @return Boolean Returns true if the current line is empty or if it is a comment line, false otherwise
490 */
491 protected function isCurrentLineEmpty()
492 {
493 return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
494 }
495
496 /**
497 * Returns true if the current line is blank.
498 *
499 * @return Boolean Returns true if the current line is blank, false otherwise
500 */
501 protected function isCurrentLineBlank()
502 {
503 return '' == trim($this->currentLine, ' ');
504 }
505
506 /**
507 * Returns true if the current line is a comment line.
508 *
509 * @return Boolean Returns true if the current line is a comment line, false otherwise
510 */
511 protected function isCurrentLineComment()
512 {
513 //checking explicitly the first char of the trim is faster than loops or strpos
514 $ltrimmedLine = ltrim($this->currentLine, ' ');
515 return $ltrimmedLine[0] === '#';
516 }
517
518 /**
519 * Cleanups a YAML string to be parsed.
520 *
521 * @param string $value The input YAML string
522 *
523 * @return string A cleaned up YAML string
524 */
525 protected function cleanup($value)
526 {
527 $value = str_replace(array("\r\n", "\r"), "\n", $value);
528
529 if (!preg_match("#\n$#", $value))
530 {
531 $value .= "\n";
532 }
533
534 // strip YAML header
535 preg_replace('#^\%YAML[: ][\d\.]+.*\n#s', '', $value);
536
537 // remove ---
538 $value = preg_replace('#^\-\-\-.*?\n#s', '', $value);
539
540 return $value;
541 }
542 }