Overview

Namespaces

  • Composer
    • Autoload
  • Guzzle
    • Common
      • Exception
    • Http
      • Curl
      • Exception
      • Message
        • Header
      • QueryAggregator
    • Parser
      • Cookie
      • Message
      • UriTemplate
      • Url
    • Plugin
      • Mock
    • Stream
  • Mockery
    • Adapter
      • Phpunit
    • CountValidator
    • Exception
    • Generator
      • StringManipulation
        • Pass
    • Loader
    • Matcher
  • None
  • Omnipay
    • Common
      • Exception
      • Message
    • Dummy
      • Message
    • Fatzebra
      • Message
  • PHP
  • Symfony
    • Component
      • EventDispatcher
        • Debug
        • DependencyInjection
        • Tests
          • Debug
          • DependencyInjection
      • HttpFoundation
        • File
          • Exception
          • MimeType
        • Session
          • Attribute
          • Flash
          • Storage
            • Handler
            • Proxy
        • Tests
          • File
            • MimeType
          • Session
            • Attribute
            • Flash
            • Storage
              • Handler
              • Proxy
      • Yaml
        • Exception
        • Tests

Classes

  • Symfony\Component\Yaml\Tests\A
  • Symfony\Component\Yaml\Tests\B
  • Symfony\Component\Yaml\Tests\DumperTest
  • Symfony\Component\Yaml\Tests\InlineTest
  • Symfony\Component\Yaml\Tests\ParseExceptionTest
  • Symfony\Component\Yaml\Tests\ParserTest
  • Symfony\Component\Yaml\Tests\YamlTest
  • Overview
  • Namespace
  • Function
  • Tree
  1: <?php
  2: 
  3: /*
  4:  * This file is part of the Symfony package.
  5:  *
  6:  * (c) Fabien Potencier <fabien@symfony.com>
  7:  *
  8:  * For the full copyright and license information, please view the LICENSE
  9:  * file that was distributed with this source code.
 10:  */
 11: 
 12: namespace Symfony\Component\Yaml;
 13: 
 14: use Symfony\Component\Yaml\Exception\ParseException;
 15: 
 16: /**
 17:  * Parser parses YAML strings to convert them to PHP arrays.
 18:  *
 19:  * @author Fabien Potencier <fabien@symfony.com>
 20:  */
 21: class Parser
 22: {
 23:     const FOLDED_SCALAR_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';
 24: 
 25:     private $offset = 0;
 26:     private $lines = array();
 27:     private $currentLineNb = -1;
 28:     private $currentLine = '';
 29:     private $refs = array();
 30: 
 31:     /**
 32:      * Constructor.
 33:      *
 34:      * @param int $offset The offset of YAML document (used for line numbers in error messages)
 35:      */
 36:     public function __construct($offset = 0)
 37:     {
 38:         $this->offset = $offset;
 39:     }
 40: 
 41:     /**
 42:      * Parses a YAML string to a PHP value.
 43:      *
 44:      * @param string $value                  A YAML string
 45:      * @param bool   $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
 46:      * @param bool   $objectSupport          true if object support is enabled, false otherwise
 47:      * @param bool   $objectForMap           true if maps should return a stdClass instead of array()
 48:      *
 49:      * @return mixed A PHP value
 50:      *
 51:      * @throws ParseException If the YAML is not valid
 52:      */
 53:     public function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false)
 54:     {
 55:         $this->currentLineNb = -1;
 56:         $this->currentLine = '';
 57:         $this->lines = explode("\n", $this->cleanup($value));
 58: 
 59:         if (!preg_match('//u', $value)) {
 60:             throw new ParseException('The YAML value does not appear to be valid UTF-8.');
 61:         }
 62: 
 63:         if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
 64:             $mbEncoding = mb_internal_encoding();
 65:             mb_internal_encoding('UTF-8');
 66:         }
 67: 
 68:         $data = array();
 69:         $context = null;
 70:         $allowOverwrite = false;
 71:         while ($this->moveToNextLine()) {
 72:             if ($this->isCurrentLineEmpty()) {
 73:                 continue;
 74:             }
 75: 
 76:             // tab?
 77:             if ("\t" === $this->currentLine[0]) {
 78:                 throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
 79:             }
 80: 
 81:             $isRef = $mergeNode = false;
 82:             if (preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+?))?\s*$#u', $this->currentLine, $values)) {
 83:                 if ($context && 'mapping' == $context) {
 84:                     throw new ParseException('You cannot define a sequence item when in a mapping');
 85:                 }
 86:                 $context = 'sequence';
 87: 
 88:                 if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
 89:                     $isRef = $matches['ref'];
 90:                     $values['value'] = $matches['value'];
 91:                 }
 92: 
 93:                 // array
 94:                 if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
 95:                     $c = $this->getRealCurrentLineNb() + 1;
 96:                     $parser = new Parser($c);
 97:                     $parser->refs = & $this->refs;
 98:                     $data[] = $parser->parse($this->getNextEmbedBlock(null, true), $exceptionOnInvalidType, $objectSupport, $objectForMap);
 99:                 } else {
100:                     if (isset($values['leadspaces'])
101:                         && preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $values['value'], $matches)
102:                     ) {
103:                         // this is a compact notation element, add to next block and parse
104:                         $c = $this->getRealCurrentLineNb();
105:                         $parser = new Parser($c);
106:                         $parser->refs = & $this->refs;
107: 
108:                         $block = $values['value'];
109:                         if ($this->isNextLineIndented()) {
110:                             $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + strlen($values['leadspaces']) + 1);
111:                         }
112: 
113:                         $data[] = $parser->parse($block, $exceptionOnInvalidType, $objectSupport, $objectForMap);
114:                     } else {
115:                         $data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap);
116:                     }
117:                 }
118:             } elseif (preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values) && (false === strpos($values['key'], ' #') || in_array($values['key'][0], array('"', "'")))) {
119:                 if ($context && 'sequence' == $context) {
120:                     throw new ParseException('You cannot define a mapping item when in a sequence');
121:                 }
122:                 $context = 'mapping';
123: 
124:                 // force correct settings
125:                 Inline::parse(null, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
126:                 try {
127:                     $key = Inline::parseScalar($values['key']);
128:                 } catch (ParseException $e) {
129:                     $e->setParsedLine($this->getRealCurrentLineNb() + 1);
130:                     $e->setSnippet($this->currentLine);
131: 
132:                     throw $e;
133:                 }
134: 
135:                 if ('<<' === $key) {
136:                     $mergeNode = true;
137:                     $allowOverwrite = true;
138:                     if (isset($values['value']) && 0 === strpos($values['value'], '*')) {
139:                         $refName = substr($values['value'], 1);
140:                         if (!array_key_exists($refName, $this->refs)) {
141:                             throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine);
142:                         }
143: 
144:                         $refValue = $this->refs[$refName];
145: 
146:                         if (!is_array($refValue)) {
147:                             throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
148:                         }
149: 
150:                         foreach ($refValue as $key => $value) {
151:                             if (!isset($data[$key])) {
152:                                 $data[$key] = $value;
153:                             }
154:                         }
155:                     } else {
156:                         if (isset($values['value']) && $values['value'] !== '') {
157:                             $value = $values['value'];
158:                         } else {
159:                             $value = $this->getNextEmbedBlock();
160:                         }
161:                         $c = $this->getRealCurrentLineNb() + 1;
162:                         $parser = new Parser($c);
163:                         $parser->refs = & $this->refs;
164:                         $parsed = $parser->parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap);
165: 
166:                         if (!is_array($parsed)) {
167:                             throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
168:                         }
169: 
170:                         if (isset($parsed[0])) {
171:                             // If the value associated with the merge key is a sequence, then this sequence is expected to contain mapping nodes
172:                             // and each of these nodes is merged in turn according to its order in the sequence. Keys in mapping nodes earlier
173:                             // in the sequence override keys specified in later mapping nodes.
174:                             foreach ($parsed as $parsedItem) {
175:                                 if (!is_array($parsedItem)) {
176:                                     throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem);
177:                                 }
178: 
179:                                 foreach ($parsedItem as $key => $value) {
180:                                     if (!isset($data[$key])) {
181:                                         $data[$key] = $value;
182:                                     }
183:                                 }
184:                             }
185:                         } else {
186:                             // If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the
187:                             // current mapping, unless the key already exists in it.
188:                             foreach ($parsed as $key => $value) {
189:                                 if (!isset($data[$key])) {
190:                                     $data[$key] = $value;
191:                                 }
192:                             }
193:                         }
194:                     }
195:                 } elseif (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
196:                     $isRef = $matches['ref'];
197:                     $values['value'] = $matches['value'];
198:                 }
199: 
200:                 if ($mergeNode) {
201:                     // Merge keys
202:                 } elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
203:                     // hash
204:                     // if next line is less indented or equal, then it means that the current value is null
205:                     if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) {
206:                         // Spec: Keys MUST be unique; first one wins.
207:                         // But overwriting is allowed when a merge node is used in current block.
208:                         if ($allowOverwrite || !isset($data[$key])) {
209:                             $data[$key] = null;
210:                         }
211:                     } else {
212:                         $c = $this->getRealCurrentLineNb() + 1;
213:                         $parser = new Parser($c);
214:                         $parser->refs = & $this->refs;
215:                         $value = $parser->parse($this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport, $objectForMap);
216:                         // Spec: Keys MUST be unique; first one wins.
217:                         // But overwriting is allowed when a merge node is used in current block.
218:                         if ($allowOverwrite || !isset($data[$key])) {
219:                             $data[$key] = $value;
220:                         }
221:                     }
222:                 } else {
223:                     $value = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap);
224:                     // Spec: Keys MUST be unique; first one wins.
225:                     // But overwriting is allowed when a merge node is used in current block.
226:                     if ($allowOverwrite || !isset($data[$key])) {
227:                         $data[$key] = $value;
228:                     }
229:                 }
230:             } else {
231:                 // multiple documents are not supported
232:                 if ('---' === $this->currentLine) {
233:                     throw new ParseException('Multiple documents are not supported.');
234:                 }
235: 
236:                 // 1-liner optionally followed by newline
237:                 $lineCount = count($this->lines);
238:                 if (1 === $lineCount || (2 === $lineCount && empty($this->lines[1]))) {
239:                     try {
240:                         $value = Inline::parse($this->lines[0], $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
241:                     } catch (ParseException $e) {
242:                         $e->setParsedLine($this->getRealCurrentLineNb() + 1);
243:                         $e->setSnippet($this->currentLine);
244: 
245:                         throw $e;
246:                     }
247: 
248:                     if (is_array($value)) {
249:                         $first = reset($value);
250:                         if (is_string($first) && 0 === strpos($first, '*')) {
251:                             $data = array();
252:                             foreach ($value as $alias) {
253:                                 $data[] = $this->refs[substr($alias, 1)];
254:                             }
255:                             $value = $data;
256:                         }
257:                     }
258: 
259:                     if (isset($mbEncoding)) {
260:                         mb_internal_encoding($mbEncoding);
261:                     }
262: 
263:                     return $value;
264:                 }
265: 
266:                 switch (preg_last_error()) {
267:                     case PREG_INTERNAL_ERROR:
268:                         $error = 'Internal PCRE error.';
269:                         break;
270:                     case PREG_BACKTRACK_LIMIT_ERROR:
271:                         $error = 'pcre.backtrack_limit reached.';
272:                         break;
273:                     case PREG_RECURSION_LIMIT_ERROR:
274:                         $error = 'pcre.recursion_limit reached.';
275:                         break;
276:                     case PREG_BAD_UTF8_ERROR:
277:                         $error = 'Malformed UTF-8 data.';
278:                         break;
279:                     case PREG_BAD_UTF8_OFFSET_ERROR:
280:                         $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
281:                         break;
282:                     default:
283:                         $error = 'Unable to parse.';
284:                 }
285: 
286:                 throw new ParseException($error, $this->getRealCurrentLineNb() + 1, $this->currentLine);
287:             }
288: 
289:             if ($isRef) {
290:                 $this->refs[$isRef] = end($data);
291:             }
292:         }
293: 
294:         if (isset($mbEncoding)) {
295:             mb_internal_encoding($mbEncoding);
296:         }
297: 
298:         return empty($data) ? null : $data;
299:     }
300: 
301:     /**
302:      * Returns the current line number (takes the offset into account).
303:      *
304:      * @return int The current line number
305:      */
306:     private function getRealCurrentLineNb()
307:     {
308:         return $this->currentLineNb + $this->offset;
309:     }
310: 
311:     /**
312:      * Returns the current line indentation.
313:      *
314:      * @return int The current line indentation
315:      */
316:     private function getCurrentLineIndentation()
317:     {
318:         return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
319:     }
320: 
321:     /**
322:      * Returns the next embed block of YAML.
323:      *
324:      * @param int  $indentation The indent level at which the block is to be read, or null for default
325:      * @param bool $inSequence  True if the enclosing data structure is a sequence
326:      *
327:      * @return string A YAML string
328:      *
329:      * @throws ParseException When indentation problem are detected
330:      */
331:     private function getNextEmbedBlock($indentation = null, $inSequence = false)
332:     {
333:         $oldLineIndentation = $this->getCurrentLineIndentation();
334: 
335:         if (!$this->moveToNextLine()) {
336:             return;
337:         }
338: 
339:         if (null === $indentation) {
340:             $newIndent = $this->getCurrentLineIndentation();
341: 
342:             $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem($this->currentLine);
343: 
344:             if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
345:                 throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
346:             }
347:         } else {
348:             $newIndent = $indentation;
349:         }
350: 
351:         $data = array();
352:         if ($this->getCurrentLineIndentation() >= $newIndent) {
353:             $data[] = substr($this->currentLine, $newIndent);
354:         } else {
355:             $this->moveToPreviousLine();
356: 
357:             return;
358:         }
359: 
360:         if ($inSequence && $oldLineIndentation === $newIndent && '-' === $data[0][0]) {
361:             // the previous line contained a dash but no item content, this line is a sequence item with the same indentation
362:             // and therefore no nested list or mapping
363:             $this->moveToPreviousLine();
364: 
365:             return;
366:         }
367: 
368:         $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem($this->currentLine);
369: 
370:         // Comments must not be removed inside a string block (ie. after a line ending with "|")
371:         $removeCommentsPattern = '~'.self::FOLDED_SCALAR_PATTERN.'$~';
372:         $removeComments = !preg_match($removeCommentsPattern, $this->currentLine);
373: 
374:         while ($this->moveToNextLine()) {
375:             $indent = $this->getCurrentLineIndentation();
376: 
377:             if ($indent === $newIndent) {
378:                 $removeComments = !preg_match($removeCommentsPattern, $this->currentLine);
379:             }
380: 
381:             if ($isItUnindentedCollection && !$this->isStringUnIndentedCollectionItem($this->currentLine) && $newIndent === $indent) {
382:                 $this->moveToPreviousLine();
383:                 break;
384:             }
385: 
386:             if ($this->isCurrentLineBlank()) {
387:                 $data[] = substr($this->currentLine, $newIndent);
388:                 continue;
389:             }
390: 
391:             if ($removeComments && $this->isCurrentLineComment()) {
392:                 continue;
393:             }
394: 
395:             if ($indent >= $newIndent) {
396:                 $data[] = substr($this->currentLine, $newIndent);
397:             } elseif (0 == $indent) {
398:                 $this->moveToPreviousLine();
399: 
400:                 break;
401:             } else {
402:                 throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
403:             }
404:         }
405: 
406:         return implode("\n", $data);
407:     }
408: 
409:     /**
410:      * Moves the parser to the next line.
411:      *
412:      * @return bool
413:      */
414:     private function moveToNextLine()
415:     {
416:         if ($this->currentLineNb >= count($this->lines) - 1) {
417:             return false;
418:         }
419: 
420:         $this->currentLine = $this->lines[++$this->currentLineNb];
421: 
422:         return true;
423:     }
424: 
425:     /**
426:      * Moves the parser to the previous line.
427:      */
428:     private function moveToPreviousLine()
429:     {
430:         $this->currentLine = $this->lines[--$this->currentLineNb];
431:     }
432: 
433:     /**
434:      * Parses a YAML value.
435:      *
436:      * @param string $value                  A YAML value
437:      * @param bool   $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise
438:      * @param bool   $objectSupport          True if object support is enabled, false otherwise
439:      * @param bool   $objectForMap           true if maps should return a stdClass instead of array()
440:      *
441:      * @return mixed A PHP value
442:      *
443:      * @throws ParseException When reference does not exist
444:      */
445:     private function parseValue($value, $exceptionOnInvalidType, $objectSupport, $objectForMap)
446:     {
447:         if (0 === strpos($value, '*')) {
448:             if (false !== $pos = strpos($value, '#')) {
449:                 $value = substr($value, 1, $pos - 2);
450:             } else {
451:                 $value = substr($value, 1);
452:             }
453: 
454:             if (!array_key_exists($value, $this->refs)) {
455:                 throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLine);
456:             }
457: 
458:             return $this->refs[$value];
459:         }
460: 
461:         if (preg_match('/^'.self::FOLDED_SCALAR_PATTERN.'$/', $value, $matches)) {
462:             $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
463: 
464:             return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers)));
465:         }
466: 
467:         try {
468:             return Inline::parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
469:         } catch (ParseException $e) {
470:             $e->setParsedLine($this->getRealCurrentLineNb() + 1);
471:             $e->setSnippet($this->currentLine);
472: 
473:             throw $e;
474:         }
475:     }
476: 
477:     /**
478:      * Parses a folded scalar.
479:      *
480:      * @param string $separator   The separator that was used to begin this folded scalar (| or >)
481:      * @param string $indicator   The indicator that was used to begin this folded scalar (+ or -)
482:      * @param int    $indentation The indentation that was used to begin this folded scalar
483:      *
484:      * @return string The text value
485:      */
486:     private function parseFoldedScalar($separator, $indicator = '', $indentation = 0)
487:     {
488:         $notEOF = $this->moveToNextLine();
489:         if (!$notEOF) {
490:             return '';
491:         }
492: 
493:         $isCurrentLineBlank = $this->isCurrentLineBlank();
494:         $text = '';
495: 
496:         // leading blank lines are consumed before determining indentation
497:         while ($notEOF && $isCurrentLineBlank) {
498:             // newline only if not EOF
499:             if ($notEOF = $this->moveToNextLine()) {
500:                 $text .= "\n";
501:                 $isCurrentLineBlank = $this->isCurrentLineBlank();
502:             }
503:         }
504: 
505:         // determine indentation if not specified
506:         if (0 === $indentation) {
507:             if (preg_match('/^ +/', $this->currentLine, $matches)) {
508:                 $indentation = strlen($matches[0]);
509:             }
510:         }
511: 
512:         if ($indentation > 0) {
513:             $pattern = sprintf('/^ {%d}(.*)$/', $indentation);
514: 
515:             while (
516:                 $notEOF && (
517:                     $isCurrentLineBlank ||
518:                     preg_match($pattern, $this->currentLine, $matches)
519:                 )
520:             ) {
521:                 if ($isCurrentLineBlank) {
522:                     $text .= substr($this->currentLine, $indentation);
523:                 } else {
524:                     $text .= $matches[1];
525:                 }
526: 
527:                 // newline only if not EOF
528:                 if ($notEOF = $this->moveToNextLine()) {
529:                     $text .= "\n";
530:                     $isCurrentLineBlank = $this->isCurrentLineBlank();
531:                 }
532:             }
533:         } elseif ($notEOF) {
534:             $text .= "\n";
535:         }
536: 
537:         if ($notEOF) {
538:             $this->moveToPreviousLine();
539:         }
540: 
541:         // replace all non-trailing single newlines with spaces in folded blocks
542:         if ('>' === $separator) {
543:             preg_match('/(\n*)$/', $text, $matches);
544:             $text = preg_replace('/(?<!\n)\n(?!\n)/', ' ', rtrim($text, "\n"));
545:             $text .= $matches[1];
546:         }
547: 
548:         // deal with trailing newlines as indicated
549:         if ('' === $indicator) {
550:             $text = preg_replace('/\n+$/s', "\n", $text);
551:         } elseif ('-' === $indicator) {
552:             $text = preg_replace('/\n+$/s', '', $text);
553:         }
554: 
555:         return $text;
556:     }
557: 
558:     /**
559:      * Returns true if the next line is indented.
560:      *
561:      * @return bool Returns true if the next line is indented, false otherwise
562:      */
563:     private function isNextLineIndented()
564:     {
565:         $currentIndentation = $this->getCurrentLineIndentation();
566:         $EOF = !$this->moveToNextLine();
567: 
568:         while (!$EOF && $this->isCurrentLineEmpty()) {
569:             $EOF = !$this->moveToNextLine();
570:         }
571: 
572:         if ($EOF) {
573:             return false;
574:         }
575: 
576:         $ret = false;
577:         if ($this->getCurrentLineIndentation() > $currentIndentation) {
578:             $ret = true;
579:         }
580: 
581:         $this->moveToPreviousLine();
582: 
583:         return $ret;
584:     }
585: 
586:     /**
587:      * Returns true if the current line is blank or if it is a comment line.
588:      *
589:      * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise
590:      */
591:     private function isCurrentLineEmpty()
592:     {
593:         return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
594:     }
595: 
596:     /**
597:      * Returns true if the current line is blank.
598:      *
599:      * @return bool Returns true if the current line is blank, false otherwise
600:      */
601:     private function isCurrentLineBlank()
602:     {
603:         return '' == trim($this->currentLine, ' ');
604:     }
605: 
606:     /**
607:      * Returns true if the current line is a comment line.
608:      *
609:      * @return bool Returns true if the current line is a comment line, false otherwise
610:      */
611:     private function isCurrentLineComment()
612:     {
613:         //checking explicitly the first char of the trim is faster than loops or strpos
614:         $ltrimmedLine = ltrim($this->currentLine, ' ');
615: 
616:         return $ltrimmedLine[0] === '#';
617:     }
618: 
619:     /**
620:      * Cleanups a YAML string to be parsed.
621:      *
622:      * @param string $value The input YAML string
623:      *
624:      * @return string A cleaned up YAML string
625:      */
626:     private function cleanup($value)
627:     {
628:         $value = str_replace(array("\r\n", "\r"), "\n", $value);
629: 
630:         // strip YAML header
631:         $count = 0;
632:         $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
633:         $this->offset += $count;
634: 
635:         // remove leading comments
636:         $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
637:         if ($count == 1) {
638:             // items have been removed, update the offset
639:             $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
640:             $value = $trimmedValue;
641:         }
642: 
643:         // remove start of the document marker (---)
644:         $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
645:         if ($count == 1) {
646:             // items have been removed, update the offset
647:             $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
648:             $value = $trimmedValue;
649: 
650:             // remove end of the document marker (...)
651:             $value = preg_replace('#\.\.\.\s*$#s', '', $value);
652:         }
653: 
654:         return $value;
655:     }
656: 
657:     /**
658:      * Returns true if the next line starts unindented collection.
659:      *
660:      * @return bool Returns true if the next line starts unindented collection, false otherwise
661:      */
662:     private function isNextLineUnIndentedCollection()
663:     {
664:         $currentIndentation = $this->getCurrentLineIndentation();
665:         $notEOF = $this->moveToNextLine();
666: 
667:         while ($notEOF && $this->isCurrentLineEmpty()) {
668:             $notEOF = $this->moveToNextLine();
669:         }
670: 
671:         if (false === $notEOF) {
672:             return false;
673:         }
674: 
675:         $ret = false;
676:         if (
677:             $this->getCurrentLineIndentation() == $currentIndentation
678:             &&
679:             $this->isStringUnIndentedCollectionItem($this->currentLine)
680:         ) {
681:             $ret = true;
682:         }
683: 
684:         $this->moveToPreviousLine();
685: 
686:         return $ret;
687:     }
688: 
689:     /**
690:      * Returns true if the string is un-indented collection item.
691:      *
692:      * @return bool Returns true if the string is un-indented collection item, false otherwise
693:      */
694:     private function isStringUnIndentedCollectionItem()
695:     {
696:         return (0 === strpos($this->currentLine, '- '));
697:     }
698: }
699: 
Omnipay Fat Zebra / Paystream Gateway Module API Documentation API documentation generated by ApiGen