菜谱项目

Parser.php 42KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. use Symfony\Component\Yaml\Tag\TaggedValue;
  13. /**
  14. * Parser parses YAML strings to convert them to PHP arrays.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class Parser
  19. {
  20. const TAG_PATTERN = '(?P<tag>![\w!.\/:-]+)';
  21. const BLOCK_SCALAR_HEADER_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';
  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. public function __construct()
  31. {
  32. if (func_num_args() > 0) {
  33. @trigger_error(sprintf('The constructor arguments $offset, $totalNumberOfLines, $skippedLineNumbers of %s are deprecated and will be removed in 4.0', self::class), E_USER_DEPRECATED);
  34. $this->offset = func_get_arg(0);
  35. if (func_num_args() > 1) {
  36. $this->totalNumberOfLines = func_get_arg(1);
  37. }
  38. if (func_num_args() > 2) {
  39. $this->skippedLineNumbers = func_get_arg(2);
  40. }
  41. }
  42. }
  43. /**
  44. * Parses a YAML string to a PHP value.
  45. *
  46. * @param string $value A YAML string
  47. * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
  48. *
  49. * @return mixed A PHP value
  50. *
  51. * @throws ParseException If the YAML is not valid
  52. */
  53. public function parse($value, $flags = 0)
  54. {
  55. if (is_bool($flags)) {
  56. @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
  57. if ($flags) {
  58. $flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
  59. } else {
  60. $flags = 0;
  61. }
  62. }
  63. if (func_num_args() >= 3) {
  64. @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
  65. if (func_get_arg(2)) {
  66. $flags |= Yaml::PARSE_OBJECT;
  67. }
  68. }
  69. if (func_num_args() >= 4) {
  70. @trigger_error('Passing a boolean flag to toggle object for map support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
  71. if (func_get_arg(3)) {
  72. $flags |= Yaml::PARSE_OBJECT_FOR_MAP;
  73. }
  74. }
  75. if (false === preg_match('//u', $value)) {
  76. throw new ParseException('The YAML value does not appear to be valid UTF-8.');
  77. }
  78. $this->refs = array();
  79. $mbEncoding = null;
  80. $e = null;
  81. $data = null;
  82. if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
  83. $mbEncoding = mb_internal_encoding();
  84. mb_internal_encoding('UTF-8');
  85. }
  86. try {
  87. $data = $this->doParse($value, $flags);
  88. } catch (\Exception $e) {
  89. } catch (\Throwable $e) {
  90. }
  91. if (null !== $mbEncoding) {
  92. mb_internal_encoding($mbEncoding);
  93. }
  94. $this->lines = array();
  95. $this->currentLine = '';
  96. $this->refs = array();
  97. $this->skippedLineNumbers = array();
  98. $this->locallySkippedLineNumbers = array();
  99. if (null !== $e) {
  100. throw $e;
  101. }
  102. return $data;
  103. }
  104. private function doParse($value, $flags)
  105. {
  106. $this->currentLineNb = -1;
  107. $this->currentLine = '';
  108. $value = $this->cleanup($value);
  109. $this->lines = explode("\n", $value);
  110. $this->locallySkippedLineNumbers = array();
  111. if (null === $this->totalNumberOfLines) {
  112. $this->totalNumberOfLines = count($this->lines);
  113. }
  114. if (!$this->moveToNextLine()) {
  115. return null;
  116. }
  117. $data = array();
  118. $context = null;
  119. $allowOverwrite = false;
  120. while ($this->isCurrentLineEmpty()) {
  121. if (!$this->moveToNextLine()) {
  122. return null;
  123. }
  124. }
  125. // Resolves the tag and returns if end of the document
  126. if (null !== ($tag = $this->getLineTag($this->currentLine, $flags, false)) && !$this->moveToNextLine()) {
  127. return new TaggedValue($tag, '');
  128. }
  129. do {
  130. if ($this->isCurrentLineEmpty()) {
  131. continue;
  132. }
  133. // tab?
  134. if ("\t" === $this->currentLine[0]) {
  135. throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  136. }
  137. $isRef = $mergeNode = false;
  138. if (self::preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+))?$#u', rtrim($this->currentLine), $values)) {
  139. if ($context && 'mapping' == $context) {
  140. throw new ParseException('You cannot define a sequence item when in a mapping', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  141. }
  142. $context = 'sequence';
  143. if (isset($values['value']) && self::preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
  144. $isRef = $matches['ref'];
  145. $values['value'] = $matches['value'];
  146. }
  147. if (isset($values['value'][1]) && '?' === $values['value'][0] && ' ' === $values['value'][1]) {
  148. @trigger_error(sprintf('Starting an unquoted string with a question mark followed by a space is deprecated since version 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0 on line %d.', $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED);
  149. }
  150. // array
  151. if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
  152. $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags);
  153. } elseif (null !== $subTag = $this->getLineTag(ltrim($values['value'], ' '), $flags)) {
  154. $data[] = new TaggedValue(
  155. $subTag,
  156. $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags)
  157. );
  158. } else {
  159. if (isset($values['leadspaces'])
  160. && self::preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->trimTag($values['value']), $matches)
  161. ) {
  162. // this is a compact notation element, add to next block and parse
  163. $block = $values['value'];
  164. if ($this->isNextLineIndented()) {
  165. $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + strlen($values['leadspaces']) + 1);
  166. }
  167. $data[] = $this->parseBlock($this->getRealCurrentLineNb(), $block, $flags);
  168. } else {
  169. $data[] = $this->parseValue($values['value'], $flags, $context);
  170. }
  171. }
  172. if ($isRef) {
  173. $this->refs[$isRef] = end($data);
  174. }
  175. } elseif (
  176. self::preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|(?:!?!php/const:)?(?:![^\s]++\s++)?[^ \'"\[\{!].*?) *\:(\s++(?P<value>.+))?$#u', rtrim($this->currentLine), $values)
  177. && (false === strpos($values['key'], ' #') || in_array($values['key'][0], array('"', "'")))
  178. ) {
  179. if ($context && 'sequence' == $context) {
  180. throw new ParseException('You cannot define a mapping item when in a sequence', $this->currentLineNb + 1, $this->currentLine);
  181. }
  182. $context = 'mapping';
  183. // force correct settings
  184. Inline::parse(null, $flags, $this->refs);
  185. try {
  186. Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
  187. $i = 0;
  188. $evaluateKey = !(Yaml::PARSE_KEYS_AS_STRINGS & $flags);
  189. // constants in key will be evaluated anyway
  190. if (isset($values['key'][0]) && '!' === $values['key'][0] && Yaml::PARSE_CONSTANT & $flags) {
  191. $evaluateKey = true;
  192. }
  193. $key = Inline::parseScalar($values['key'], 0, null, $i, $evaluateKey);
  194. } catch (ParseException $e) {
  195. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  196. $e->setSnippet($this->currentLine);
  197. throw $e;
  198. }
  199. if (!(Yaml::PARSE_KEYS_AS_STRINGS & $flags) && !is_string($key) && !is_int($key)) {
  200. $keyType = is_numeric($key) ? 'numeric key' : 'non-string key';
  201. @trigger_error(sprintf('Implicit casting of %s to string is deprecated since version 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Quote your evaluable mapping keys instead on line %d.', $keyType, $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED);
  202. }
  203. // Convert float keys to strings, to avoid being converted to integers by PHP
  204. if (is_float($key)) {
  205. $key = (string) $key;
  206. }
  207. if ('<<' === $key && (!isset($values['value']) || !self::preg_match('#^&(?P<ref>[^ ]+)#u', $values['value'], $refMatches))) {
  208. $mergeNode = true;
  209. $allowOverwrite = true;
  210. if (isset($values['value'][0]) && '*' === $values['value'][0]) {
  211. $refName = substr(rtrim($values['value']), 1);
  212. if (!array_key_exists($refName, $this->refs)) {
  213. throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine);
  214. }
  215. $refValue = $this->refs[$refName];
  216. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $refValue instanceof \stdClass) {
  217. $refValue = (array) $refValue;
  218. }
  219. if (!is_array($refValue)) {
  220. throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  221. }
  222. $data += $refValue; // array union
  223. } else {
  224. if (isset($values['value']) && '' !== $values['value']) {
  225. $value = $values['value'];
  226. } else {
  227. $value = $this->getNextEmbedBlock();
  228. }
  229. $parsed = $this->parseBlock($this->getRealCurrentLineNb() + 1, $value, $flags);
  230. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $parsed instanceof \stdClass) {
  231. $parsed = (array) $parsed;
  232. }
  233. if (!is_array($parsed)) {
  234. throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  235. }
  236. if (isset($parsed[0])) {
  237. // If the value associated with the merge key is a sequence, then this sequence is expected to contain mapping nodes
  238. // and each of these nodes is merged in turn according to its order in the sequence. Keys in mapping nodes earlier
  239. // in the sequence override keys specified in later mapping nodes.
  240. foreach ($parsed as $parsedItem) {
  241. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $parsedItem instanceof \stdClass) {
  242. $parsedItem = (array) $parsedItem;
  243. }
  244. if (!is_array($parsedItem)) {
  245. throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem);
  246. }
  247. $data += $parsedItem; // array union
  248. }
  249. } else {
  250. // If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the
  251. // current mapping, unless the key already exists in it.
  252. $data += $parsed; // array union
  253. }
  254. }
  255. } elseif ('<<' !== $key && isset($values['value']) && self::preg_match('#^&(?P<ref>[^ ]++) *+(?P<value>.*)#u', $values['value'], $matches)) {
  256. $isRef = $matches['ref'];
  257. $values['value'] = $matches['value'];
  258. }
  259. $subTag = null;
  260. if ($mergeNode) {
  261. // Merge keys
  262. } elseif (!isset($values['value']) || '' === $values['value'] || 0 === strpos($values['value'], '#') || (null !== $subTag = $this->getLineTag($values['value'], $flags)) || '<<' === $key) {
  263. // hash
  264. // if next line is less indented or equal, then it means that the current value is null
  265. if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) {
  266. // Spec: Keys MUST be unique; first one wins.
  267. // But overwriting is allowed when a merge node is used in current block.
  268. if ($allowOverwrite || !isset($data[$key])) {
  269. if (null !== $subTag) {
  270. $data[$key] = new TaggedValue($subTag, '');
  271. } else {
  272. $data[$key] = null;
  273. }
  274. } else {
  275. @trigger_error(sprintf('Duplicate key "%s" detected whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0 on line %d.', $key, $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED);
  276. }
  277. } else {
  278. // remember the parsed line number here in case we need it to provide some contexts in error messages below
  279. $realCurrentLineNbKey = $this->getRealCurrentLineNb();
  280. $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $flags);
  281. if ('<<' === $key) {
  282. $this->refs[$refMatches['ref']] = $value;
  283. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $value instanceof \stdClass) {
  284. $value = (array) $value;
  285. }
  286. $data += $value;
  287. } elseif ($allowOverwrite || !isset($data[$key])) {
  288. // Spec: Keys MUST be unique; first one wins.
  289. // But overwriting is allowed when a merge node is used in current block.
  290. if (null !== $subTag) {
  291. $data[$key] = new TaggedValue($subTag, $value);
  292. } else {
  293. $data[$key] = $value;
  294. }
  295. } else {
  296. @trigger_error(sprintf('Duplicate key "%s" detected whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0 on line %d.', $key, $realCurrentLineNbKey + 1), E_USER_DEPRECATED);
  297. }
  298. }
  299. } else {
  300. $value = $this->parseValue(rtrim($values['value']), $flags, $context);
  301. // Spec: Keys MUST be unique; first one wins.
  302. // But overwriting is allowed when a merge node is used in current block.
  303. if ($allowOverwrite || !isset($data[$key])) {
  304. $data[$key] = $value;
  305. } else {
  306. @trigger_error(sprintf('Duplicate key "%s" detected whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0 on line %d.', $key, $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED);
  307. }
  308. }
  309. if ($isRef) {
  310. $this->refs[$isRef] = $data[$key];
  311. }
  312. } else {
  313. // multiple documents are not supported
  314. if ('---' === $this->currentLine) {
  315. throw new ParseException('Multiple documents are not supported.', $this->currentLineNb + 1, $this->currentLine);
  316. }
  317. if (isset($this->currentLine[1]) && '?' === $this->currentLine[0] && ' ' === $this->currentLine[1]) {
  318. @trigger_error(sprintf('Starting an unquoted string with a question mark followed by a space is deprecated since version 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0 on line %d.', $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED);
  319. }
  320. // 1-liner optionally followed by newline(s)
  321. if (is_string($value) && $this->lines[0] === trim($value)) {
  322. try {
  323. Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
  324. $value = Inline::parse($this->lines[0], $flags, $this->refs);
  325. } catch (ParseException $e) {
  326. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  327. $e->setSnippet($this->currentLine);
  328. throw $e;
  329. }
  330. return $value;
  331. }
  332. // try to parse the value as a multi-line string as a last resort
  333. if (0 === $this->currentLineNb) {
  334. $parseError = false;
  335. $previousLineWasNewline = false;
  336. $previousLineWasTerminatedWithBackslash = false;
  337. $value = '';
  338. foreach ($this->lines as $line) {
  339. try {
  340. if (isset($line[0]) && ('"' === $line[0] || "'" === $line[0])) {
  341. $parsedLine = $line;
  342. } else {
  343. $parsedLine = Inline::parse($line, $flags, $this->refs);
  344. }
  345. if (!is_string($parsedLine)) {
  346. $parseError = true;
  347. break;
  348. }
  349. if ('' === trim($parsedLine)) {
  350. $value .= "\n";
  351. } elseif (!$previousLineWasNewline && !$previousLineWasTerminatedWithBackslash) {
  352. $value .= ' ';
  353. }
  354. if ('' !== trim($parsedLine) && '\\' === substr($parsedLine, -1)) {
  355. $value .= ltrim(substr($parsedLine, 0, -1));
  356. } elseif ('' !== trim($parsedLine)) {
  357. $value .= trim($parsedLine);
  358. }
  359. if ('' === trim($parsedLine)) {
  360. $previousLineWasNewline = true;
  361. $previousLineWasTerminatedWithBackslash = false;
  362. } elseif ('\\' === substr($parsedLine, -1)) {
  363. $previousLineWasNewline = false;
  364. $previousLineWasTerminatedWithBackslash = true;
  365. } else {
  366. $previousLineWasNewline = false;
  367. $previousLineWasTerminatedWithBackslash = false;
  368. }
  369. } catch (ParseException $e) {
  370. $parseError = true;
  371. break;
  372. }
  373. }
  374. if (!$parseError) {
  375. return Inline::parse(trim($value));
  376. }
  377. }
  378. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  379. }
  380. } while ($this->moveToNextLine());
  381. if (null !== $tag) {
  382. $data = new TaggedValue($tag, $data);
  383. }
  384. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && !is_object($data) && 'mapping' === $context) {
  385. $object = new \stdClass();
  386. foreach ($data as $key => $value) {
  387. $object->$key = $value;
  388. }
  389. $data = $object;
  390. }
  391. return empty($data) ? null : $data;
  392. }
  393. private function parseBlock($offset, $yaml, $flags)
  394. {
  395. $skippedLineNumbers = $this->skippedLineNumbers;
  396. foreach ($this->locallySkippedLineNumbers as $lineNumber) {
  397. if ($lineNumber < $offset) {
  398. continue;
  399. }
  400. $skippedLineNumbers[] = $lineNumber;
  401. }
  402. $parser = new self();
  403. $parser->offset = $offset;
  404. $parser->totalNumberOfLines = $this->totalNumberOfLines;
  405. $parser->skippedLineNumbers = $skippedLineNumbers;
  406. $parser->refs = &$this->refs;
  407. return $parser->doParse($yaml, $flags);
  408. }
  409. /**
  410. * Returns the current line number (takes the offset into account).
  411. *
  412. * @return int The current line number
  413. */
  414. private function getRealCurrentLineNb()
  415. {
  416. $realCurrentLineNumber = $this->currentLineNb + $this->offset;
  417. foreach ($this->skippedLineNumbers as $skippedLineNumber) {
  418. if ($skippedLineNumber > $realCurrentLineNumber) {
  419. break;
  420. }
  421. ++$realCurrentLineNumber;
  422. }
  423. return $realCurrentLineNumber;
  424. }
  425. /**
  426. * Returns the current line indentation.
  427. *
  428. * @return int The current line indentation
  429. */
  430. private function getCurrentLineIndentation()
  431. {
  432. return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
  433. }
  434. /**
  435. * Returns the next embed block of YAML.
  436. *
  437. * @param int $indentation The indent level at which the block is to be read, or null for default
  438. * @param bool $inSequence True if the enclosing data structure is a sequence
  439. *
  440. * @return string A YAML string
  441. *
  442. * @throws ParseException When indentation problem are detected
  443. */
  444. private function getNextEmbedBlock($indentation = null, $inSequence = false)
  445. {
  446. $oldLineIndentation = $this->getCurrentLineIndentation();
  447. $blockScalarIndentations = array();
  448. if ($this->isBlockScalarHeader()) {
  449. $blockScalarIndentations[] = $oldLineIndentation;
  450. }
  451. if (!$this->moveToNextLine()) {
  452. return;
  453. }
  454. if (null === $indentation) {
  455. $newIndent = $this->getCurrentLineIndentation();
  456. $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem();
  457. if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
  458. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  459. }
  460. } else {
  461. $newIndent = $indentation;
  462. }
  463. $data = array();
  464. if ($this->getCurrentLineIndentation() >= $newIndent) {
  465. $data[] = substr($this->currentLine, $newIndent);
  466. } else {
  467. $this->moveToPreviousLine();
  468. return;
  469. }
  470. if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) {
  471. // the previous line contained a dash but no item content, this line is a sequence item with the same indentation
  472. // and therefore no nested list or mapping
  473. $this->moveToPreviousLine();
  474. return;
  475. }
  476. $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
  477. if (empty($blockScalarIndentations) && $this->isBlockScalarHeader()) {
  478. $blockScalarIndentations[] = $this->getCurrentLineIndentation();
  479. }
  480. $previousLineIndentation = $this->getCurrentLineIndentation();
  481. while ($this->moveToNextLine()) {
  482. $indent = $this->getCurrentLineIndentation();
  483. // terminate all block scalars that are more indented than the current line
  484. if (!empty($blockScalarIndentations) && $indent < $previousLineIndentation && '' !== trim($this->currentLine)) {
  485. foreach ($blockScalarIndentations as $key => $blockScalarIndentation) {
  486. if ($blockScalarIndentation >= $indent) {
  487. unset($blockScalarIndentations[$key]);
  488. }
  489. }
  490. }
  491. if (empty($blockScalarIndentations) && !$this->isCurrentLineComment() && $this->isBlockScalarHeader()) {
  492. $blockScalarIndentations[] = $indent;
  493. }
  494. $previousLineIndentation = $indent;
  495. if ($isItUnindentedCollection && !$this->isCurrentLineEmpty() && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) {
  496. $this->moveToPreviousLine();
  497. break;
  498. }
  499. if ($this->isCurrentLineBlank()) {
  500. $data[] = substr($this->currentLine, $newIndent);
  501. continue;
  502. }
  503. // we ignore "comment" lines only when we are not inside a scalar block
  504. if (empty($blockScalarIndentations) && $this->isCurrentLineComment()) {
  505. // remember ignored comment lines (they are used later in nested
  506. // parser calls to determine real line numbers)
  507. //
  508. // CAUTION: beware to not populate the global property here as it
  509. // will otherwise influence the getRealCurrentLineNb() call here
  510. // for consecutive comment lines and subsequent embedded blocks
  511. $this->locallySkippedLineNumbers[] = $this->getRealCurrentLineNb();
  512. continue;
  513. }
  514. if ($indent >= $newIndent) {
  515. $data[] = substr($this->currentLine, $newIndent);
  516. } elseif (0 == $indent) {
  517. $this->moveToPreviousLine();
  518. break;
  519. } else {
  520. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  521. }
  522. }
  523. return implode("\n", $data);
  524. }
  525. /**
  526. * Moves the parser to the next line.
  527. *
  528. * @return bool
  529. */
  530. private function moveToNextLine()
  531. {
  532. if ($this->currentLineNb >= count($this->lines) - 1) {
  533. return false;
  534. }
  535. $this->currentLine = $this->lines[++$this->currentLineNb];
  536. return true;
  537. }
  538. /**
  539. * Moves the parser to the previous line.
  540. *
  541. * @return bool
  542. */
  543. private function moveToPreviousLine()
  544. {
  545. if ($this->currentLineNb < 1) {
  546. return false;
  547. }
  548. $this->currentLine = $this->lines[--$this->currentLineNb];
  549. return true;
  550. }
  551. /**
  552. * Parses a YAML value.
  553. *
  554. * @param string $value A YAML value
  555. * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
  556. * @param string $context The parser context (either sequence or mapping)
  557. *
  558. * @return mixed A PHP value
  559. *
  560. * @throws ParseException When reference does not exist
  561. */
  562. private function parseValue($value, $flags, $context)
  563. {
  564. if (0 === strpos($value, '*')) {
  565. if (false !== $pos = strpos($value, '#')) {
  566. $value = substr($value, 1, $pos - 2);
  567. } else {
  568. $value = substr($value, 1);
  569. }
  570. if (!array_key_exists($value, $this->refs)) {
  571. throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine);
  572. }
  573. return $this->refs[$value];
  574. }
  575. if (self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
  576. $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
  577. $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
  578. if ('' !== $matches['tag']) {
  579. if ('!!binary' === $matches['tag']) {
  580. return Inline::evaluateBinaryScalar($data);
  581. } elseif ('!' !== $matches['tag']) {
  582. @trigger_error(sprintf('Using the custom tag "%s" for the value "%s" is deprecated since version 3.3. It will be replaced by an instance of %s in 4.0 on line %d.', $matches['tag'], $data, TaggedValue::class, $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED);
  583. }
  584. }
  585. return $data;
  586. }
  587. try {
  588. $quotation = '' !== $value && ('"' === $value[0] || "'" === $value[0]) ? $value[0] : null;
  589. // do not take following lines into account when the current line is a quoted single line value
  590. if (null !== $quotation && self::preg_match('/^'.$quotation.'.*'.$quotation.'(\s*#.*)?$/', $value)) {
  591. return Inline::parse($value, $flags, $this->refs);
  592. }
  593. while ($this->moveToNextLine()) {
  594. // unquoted strings end before the first unindented line
  595. if (null === $quotation && 0 === $this->getCurrentLineIndentation()) {
  596. $this->moveToPreviousLine();
  597. break;
  598. }
  599. $value .= ' '.trim($this->currentLine);
  600. // quoted string values end with a line that is terminated with the quotation character
  601. if ('' !== $this->currentLine && substr($this->currentLine, -1) === $quotation) {
  602. break;
  603. }
  604. }
  605. Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
  606. $parsedValue = Inline::parse($value, $flags, $this->refs);
  607. if ('mapping' === $context && is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
  608. throw new ParseException('A colon cannot be used in an unquoted mapping value.');
  609. }
  610. return $parsedValue;
  611. } catch (ParseException $e) {
  612. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  613. $e->setSnippet($this->currentLine);
  614. throw $e;
  615. }
  616. }
  617. /**
  618. * Parses a block scalar.
  619. *
  620. * @param string $style The style indicator that was used to begin this block scalar (| or >)
  621. * @param string $chomping The chomping indicator that was used to begin this block scalar (+ or -)
  622. * @param int $indentation The indentation indicator that was used to begin this block scalar
  623. *
  624. * @return string The text value
  625. */
  626. private function parseBlockScalar($style, $chomping = '', $indentation = 0)
  627. {
  628. $notEOF = $this->moveToNextLine();
  629. if (!$notEOF) {
  630. return '';
  631. }
  632. $isCurrentLineBlank = $this->isCurrentLineBlank();
  633. $blockLines = array();
  634. // leading blank lines are consumed before determining indentation
  635. while ($notEOF && $isCurrentLineBlank) {
  636. // newline only if not EOF
  637. if ($notEOF = $this->moveToNextLine()) {
  638. $blockLines[] = '';
  639. $isCurrentLineBlank = $this->isCurrentLineBlank();
  640. }
  641. }
  642. // determine indentation if not specified
  643. if (0 === $indentation) {
  644. if (self::preg_match('/^ +/', $this->currentLine, $matches)) {
  645. $indentation = strlen($matches[0]);
  646. }
  647. }
  648. if ($indentation > 0) {
  649. $pattern = sprintf('/^ {%d}(.*)$/', $indentation);
  650. while (
  651. $notEOF && (
  652. $isCurrentLineBlank ||
  653. self::preg_match($pattern, $this->currentLine, $matches)
  654. )
  655. ) {
  656. if ($isCurrentLineBlank && strlen($this->currentLine) > $indentation) {
  657. $blockLines[] = substr($this->currentLine, $indentation);
  658. } elseif ($isCurrentLineBlank) {
  659. $blockLines[] = '';
  660. } else {
  661. $blockLines[] = $matches[1];
  662. }
  663. // newline only if not EOF
  664. if ($notEOF = $this->moveToNextLine()) {
  665. $isCurrentLineBlank = $this->isCurrentLineBlank();
  666. }
  667. }
  668. } elseif ($notEOF) {
  669. $blockLines[] = '';
  670. }
  671. if ($notEOF) {
  672. $blockLines[] = '';
  673. $this->moveToPreviousLine();
  674. } elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) {
  675. $blockLines[] = '';
  676. }
  677. // folded style
  678. if ('>' === $style) {
  679. $text = '';
  680. $previousLineIndented = false;
  681. $previousLineBlank = false;
  682. for ($i = 0, $blockLinesCount = count($blockLines); $i < $blockLinesCount; ++$i) {
  683. if ('' === $blockLines[$i]) {
  684. $text .= "\n";
  685. $previousLineIndented = false;
  686. $previousLineBlank = true;
  687. } elseif (' ' === $blockLines[$i][0]) {
  688. $text .= "\n".$blockLines[$i];
  689. $previousLineIndented = true;
  690. $previousLineBlank = false;
  691. } elseif ($previousLineIndented) {
  692. $text .= "\n".$blockLines[$i];
  693. $previousLineIndented = false;
  694. $previousLineBlank = false;
  695. } elseif ($previousLineBlank || 0 === $i) {
  696. $text .= $blockLines[$i];
  697. $previousLineIndented = false;
  698. $previousLineBlank = false;
  699. } else {
  700. $text .= ' '.$blockLines[$i];
  701. $previousLineIndented = false;
  702. $previousLineBlank = false;
  703. }
  704. }
  705. } else {
  706. $text = implode("\n", $blockLines);
  707. }
  708. // deal with trailing newlines
  709. if ('' === $chomping) {
  710. $text = preg_replace('/\n+$/', "\n", $text);
  711. } elseif ('-' === $chomping) {
  712. $text = preg_replace('/\n+$/', '', $text);
  713. }
  714. return $text;
  715. }
  716. /**
  717. * Returns true if the next line is indented.
  718. *
  719. * @return bool Returns true if the next line is indented, false otherwise
  720. */
  721. private function isNextLineIndented()
  722. {
  723. $currentIndentation = $this->getCurrentLineIndentation();
  724. $EOF = !$this->moveToNextLine();
  725. while (!$EOF && $this->isCurrentLineEmpty()) {
  726. $EOF = !$this->moveToNextLine();
  727. }
  728. if ($EOF) {
  729. return false;
  730. }
  731. $ret = $this->getCurrentLineIndentation() > $currentIndentation;
  732. $this->moveToPreviousLine();
  733. return $ret;
  734. }
  735. /**
  736. * Returns true if the current line is blank or if it is a comment line.
  737. *
  738. * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise
  739. */
  740. private function isCurrentLineEmpty()
  741. {
  742. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  743. }
  744. /**
  745. * Returns true if the current line is blank.
  746. *
  747. * @return bool Returns true if the current line is blank, false otherwise
  748. */
  749. private function isCurrentLineBlank()
  750. {
  751. return '' == trim($this->currentLine, ' ');
  752. }
  753. /**
  754. * Returns true if the current line is a comment line.
  755. *
  756. * @return bool Returns true if the current line is a comment line, false otherwise
  757. */
  758. private function isCurrentLineComment()
  759. {
  760. //checking explicitly the first char of the trim is faster than loops or strpos
  761. $ltrimmedLine = ltrim($this->currentLine, ' ');
  762. return '' !== $ltrimmedLine && '#' === $ltrimmedLine[0];
  763. }
  764. private function isCurrentLineLastLineInDocument()
  765. {
  766. return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1);
  767. }
  768. /**
  769. * Cleanups a YAML string to be parsed.
  770. *
  771. * @param string $value The input YAML string
  772. *
  773. * @return string A cleaned up YAML string
  774. */
  775. private function cleanup($value)
  776. {
  777. $value = str_replace(array("\r\n", "\r"), "\n", $value);
  778. // strip YAML header
  779. $count = 0;
  780. $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
  781. $this->offset += $count;
  782. // remove leading comments
  783. $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
  784. if (1 === $count) {
  785. // items have been removed, update the offset
  786. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  787. $value = $trimmedValue;
  788. }
  789. // remove start of the document marker (---)
  790. $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
  791. if (1 === $count) {
  792. // items have been removed, update the offset
  793. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  794. $value = $trimmedValue;
  795. // remove end of the document marker (...)
  796. $value = preg_replace('#\.\.\.\s*$#', '', $value);
  797. }
  798. return $value;
  799. }
  800. /**
  801. * Returns true if the next line starts unindented collection.
  802. *
  803. * @return bool Returns true if the next line starts unindented collection, false otherwise
  804. */
  805. private function isNextLineUnIndentedCollection()
  806. {
  807. $currentIndentation = $this->getCurrentLineIndentation();
  808. $notEOF = $this->moveToNextLine();
  809. while ($notEOF && $this->isCurrentLineEmpty()) {
  810. $notEOF = $this->moveToNextLine();
  811. }
  812. if (false === $notEOF) {
  813. return false;
  814. }
  815. $ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem();
  816. $this->moveToPreviousLine();
  817. return $ret;
  818. }
  819. /**
  820. * Returns true if the string is un-indented collection item.
  821. *
  822. * @return bool Returns true if the string is un-indented collection item, false otherwise
  823. */
  824. private function isStringUnIndentedCollectionItem()
  825. {
  826. return '-' === rtrim($this->currentLine) || 0 === strpos($this->currentLine, '- ');
  827. }
  828. /**
  829. * Tests whether or not the current line is the header of a block scalar.
  830. *
  831. * @return bool
  832. */
  833. private function isBlockScalarHeader()
  834. {
  835. return (bool) self::preg_match('~'.self::BLOCK_SCALAR_HEADER_PATTERN.'$~', $this->currentLine);
  836. }
  837. /**
  838. * A local wrapper for `preg_match` which will throw a ParseException if there
  839. * is an internal error in the PCRE engine.
  840. *
  841. * This avoids us needing to check for "false" every time PCRE is used
  842. * in the YAML engine
  843. *
  844. * @throws ParseException on a PCRE internal error
  845. *
  846. * @see preg_last_error()
  847. *
  848. * @internal
  849. */
  850. public static function preg_match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0)
  851. {
  852. if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) {
  853. switch (preg_last_error()) {
  854. case PREG_INTERNAL_ERROR:
  855. $error = 'Internal PCRE error.';
  856. break;
  857. case PREG_BACKTRACK_LIMIT_ERROR:
  858. $error = 'pcre.backtrack_limit reached.';
  859. break;
  860. case PREG_RECURSION_LIMIT_ERROR:
  861. $error = 'pcre.recursion_limit reached.';
  862. break;
  863. case PREG_BAD_UTF8_ERROR:
  864. $error = 'Malformed UTF-8 data.';
  865. break;
  866. case PREG_BAD_UTF8_OFFSET_ERROR:
  867. $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
  868. break;
  869. default:
  870. $error = 'Error.';
  871. }
  872. throw new ParseException($error);
  873. }
  874. return $ret;
  875. }
  876. /**
  877. * Trim the tag on top of the value.
  878. *
  879. * Prevent values such as `!foo {quz: bar}` to be considered as
  880. * a mapping block.
  881. */
  882. private function trimTag($value)
  883. {
  884. if ('!' === $value[0]) {
  885. return ltrim(substr($value, 1, strcspn($value, " \r\n", 1)), ' ');
  886. }
  887. return $value;
  888. }
  889. private function getLineTag($value, $flags, $nextLineCheck = true)
  890. {
  891. if ('' === $value || '!' !== $value[0] || 1 !== self::preg_match('/^'.self::TAG_PATTERN.' *( +#.*)?$/', $value, $matches)) {
  892. return;
  893. }
  894. if ($nextLineCheck && !$this->isNextLineIndented()) {
  895. return;
  896. }
  897. $tag = substr($matches['tag'], 1);
  898. // Built-in tags
  899. if ($tag && '!' === $tag[0]) {
  900. throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag));
  901. }
  902. if (Yaml::PARSE_CUSTOM_TAGS & $flags) {
  903. return $tag;
  904. }
  905. throw new ParseException(sprintf('Tags support is not enabled. You must use the flag `Yaml::PARSE_CUSTOM_TAGS` to use "%s".', $matches['tag']));
  906. }
  907. }