Drupal investigation

Parser.php 31KB

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