Parser.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  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. * @final
  19. */
  20. class Parser
  21. {
  22. public const TAG_PATTERN = '(?P<tag>![\w!.\/:-]+)';
  23. public const BLOCK_SCALAR_HEADER_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';
  24. public const REFERENCE_PATTERN = '#^&(?P<ref>[^ ]++) *+(?P<value>.*)#u';
  25. private $filename;
  26. private $offset = 0;
  27. private $numberOfParsedLines = 0;
  28. private $totalNumberOfLines;
  29. private $lines = [];
  30. private $currentLineNb = -1;
  31. private $currentLine = '';
  32. private $refs = [];
  33. private $skippedLineNumbers = [];
  34. private $locallySkippedLineNumbers = [];
  35. private $refsBeingParsed = [];
  36. /**
  37. * Parses a YAML file into a PHP value.
  38. *
  39. * @param string $filename The path to the YAML file to be parsed
  40. * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
  41. *
  42. * @return mixed The YAML converted to a PHP value
  43. *
  44. * @throws ParseException If the file could not be read or the YAML is not valid
  45. */
  46. public function parseFile(string $filename, int $flags = 0)
  47. {
  48. if (!is_file($filename)) {
  49. throw new ParseException(sprintf('File "%s" does not exist.', $filename));
  50. }
  51. if (!is_readable($filename)) {
  52. throw new ParseException(sprintf('File "%s" cannot be read.', $filename));
  53. }
  54. $this->filename = $filename;
  55. try {
  56. return $this->parse(file_get_contents($filename), $flags);
  57. } finally {
  58. $this->filename = null;
  59. }
  60. }
  61. /**
  62. * Parses a YAML string to a PHP value.
  63. *
  64. * @param string $value A YAML string
  65. * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
  66. *
  67. * @return mixed A PHP value
  68. *
  69. * @throws ParseException If the YAML is not valid
  70. */
  71. public function parse(string $value, int $flags = 0)
  72. {
  73. if (false === preg_match('//u', $value)) {
  74. throw new ParseException('The YAML value does not appear to be valid UTF-8.', -1, null, $this->filename);
  75. }
  76. $this->refs = [];
  77. $mbEncoding = null;
  78. if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
  79. $mbEncoding = mb_internal_encoding();
  80. mb_internal_encoding('UTF-8');
  81. }
  82. try {
  83. $data = $this->doParse($value, $flags);
  84. } finally {
  85. if (null !== $mbEncoding) {
  86. mb_internal_encoding($mbEncoding);
  87. }
  88. $this->lines = [];
  89. $this->currentLine = '';
  90. $this->numberOfParsedLines = 0;
  91. $this->refs = [];
  92. $this->skippedLineNumbers = [];
  93. $this->locallySkippedLineNumbers = [];
  94. $this->totalNumberOfLines = null;
  95. }
  96. return $data;
  97. }
  98. private function doParse(string $value, int $flags)
  99. {
  100. $this->currentLineNb = -1;
  101. $this->currentLine = '';
  102. $value = $this->cleanup($value);
  103. $this->lines = explode("\n", $value);
  104. $this->numberOfParsedLines = \count($this->lines);
  105. $this->locallySkippedLineNumbers = [];
  106. if (null === $this->totalNumberOfLines) {
  107. $this->totalNumberOfLines = $this->numberOfParsedLines;
  108. }
  109. if (!$this->moveToNextLine()) {
  110. return null;
  111. }
  112. $data = [];
  113. $context = null;
  114. $allowOverwrite = false;
  115. while ($this->isCurrentLineEmpty()) {
  116. if (!$this->moveToNextLine()) {
  117. return null;
  118. }
  119. }
  120. // Resolves the tag and returns if end of the document
  121. if (null !== ($tag = $this->getLineTag($this->currentLine, $flags, false)) && !$this->moveToNextLine()) {
  122. return new TaggedValue($tag, '');
  123. }
  124. do {
  125. if ($this->isCurrentLineEmpty()) {
  126. continue;
  127. }
  128. // tab?
  129. if ("\t" === $this->currentLine[0]) {
  130. throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  131. }
  132. Inline::initialize($flags, $this->getRealCurrentLineNb(), $this->filename);
  133. $isRef = $mergeNode = false;
  134. if ('-' === $this->currentLine[0] && self::preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+))?$#u', rtrim($this->currentLine), $values)) {
  135. if ($context && 'mapping' == $context) {
  136. throw new ParseException('You cannot define a sequence item when in a mapping.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  137. }
  138. $context = 'sequence';
  139. if (isset($values['value']) && '&' === $values['value'][0] && self::preg_match(self::REFERENCE_PATTERN, $values['value'], $matches)) {
  140. $isRef = $matches['ref'];
  141. $this->refsBeingParsed[] = $isRef;
  142. $values['value'] = $matches['value'];
  143. }
  144. if (isset($values['value'][1]) && '?' === $values['value'][0] && ' ' === $values['value'][1]) {
  145. throw new ParseException('Complex mappings are not supported.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  146. }
  147. // array
  148. if (isset($values['value']) && 0 === strpos(ltrim($values['value'], ' '), '-')) {
  149. // Inline first child
  150. $currentLineNumber = $this->getRealCurrentLineNb();
  151. $sequenceIndentation = \strlen($values['leadspaces']) + 1;
  152. $sequenceYaml = substr($this->currentLine, $sequenceIndentation);
  153. $sequenceYaml .= "\n".$this->getNextEmbedBlock($sequenceIndentation, true);
  154. $data[] = $this->parseBlock($currentLineNumber, rtrim($sequenceYaml), $flags);
  155. } elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
  156. $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true) ?? '', $flags);
  157. } elseif (null !== $subTag = $this->getLineTag(ltrim($values['value'], ' '), $flags)) {
  158. $data[] = new TaggedValue(
  159. $subTag,
  160. $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags)
  161. );
  162. } else {
  163. if (
  164. isset($values['leadspaces'])
  165. && (
  166. '!' === $values['value'][0]
  167. || self::preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->trimTag($values['value']), $matches)
  168. )
  169. ) {
  170. // this is a compact notation element, add to next block and parse
  171. $block = $values['value'];
  172. if ($this->isNextLineIndented()) {
  173. $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + \strlen($values['leadspaces']) + 1);
  174. }
  175. $data[] = $this->parseBlock($this->getRealCurrentLineNb(), $block, $flags);
  176. } else {
  177. $data[] = $this->parseValue($values['value'], $flags, $context);
  178. }
  179. }
  180. if ($isRef) {
  181. $this->refs[$isRef] = end($data);
  182. array_pop($this->refsBeingParsed);
  183. }
  184. } elseif (
  185. self::preg_match('#^(?P<key>(?:![^\s]++\s++)?(?:'.Inline::REGEX_QUOTED_STRING.'|(?:!?!php/const:)?[^ \'"\[\{!].*?)) *\:(( |\t)++(?P<value>.+))?$#u', rtrim($this->currentLine), $values)
  186. && (false === strpos($values['key'], ' #') || \in_array($values['key'][0], ['"', "'"]))
  187. ) {
  188. if ($context && 'sequence' == $context) {
  189. throw new ParseException('You cannot define a mapping item when in a sequence.', $this->currentLineNb + 1, $this->currentLine, $this->filename);
  190. }
  191. $context = 'mapping';
  192. try {
  193. $key = Inline::parseScalar($values['key']);
  194. } catch (ParseException $e) {
  195. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  196. $e->setSnippet($this->currentLine);
  197. throw $e;
  198. }
  199. if (!\is_string($key) && !\is_int($key)) {
  200. throw new ParseException((is_numeric($key) ? 'Numeric' : 'Non-string').' keys are not supported. Quote your evaluable mapping keys instead.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  201. }
  202. // Convert float keys to strings, to avoid being converted to integers by PHP
  203. if (\is_float($key)) {
  204. $key = (string) $key;
  205. }
  206. if ('<<' === $key && (!isset($values['value']) || '&' !== $values['value'][0] || !self::preg_match('#^&(?P<ref>[^ ]+)#u', $values['value'], $refMatches))) {
  207. $mergeNode = true;
  208. $allowOverwrite = true;
  209. if (isset($values['value'][0]) && '*' === $values['value'][0]) {
  210. $refName = substr(rtrim($values['value']), 1);
  211. if (!\array_key_exists($refName, $this->refs)) {
  212. if (false !== $pos = array_search($refName, $this->refsBeingParsed, true)) {
  213. throw new ParseException(sprintf('Circular reference [%s] detected for reference "%s".', implode(', ', array_merge(\array_slice($this->refsBeingParsed, $pos), [$refName])), $refName), $this->currentLineNb + 1, $this->currentLine, $this->filename);
  214. }
  215. throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  216. }
  217. $refValue = $this->refs[$refName];
  218. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $refValue instanceof \stdClass) {
  219. $refValue = (array) $refValue;
  220. }
  221. if (!\is_array($refValue)) {
  222. throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  223. }
  224. $data += $refValue; // array union
  225. } else {
  226. if (isset($values['value']) && '' !== $values['value']) {
  227. $value = $values['value'];
  228. } else {
  229. $value = $this->getNextEmbedBlock();
  230. }
  231. $parsed = $this->parseBlock($this->getRealCurrentLineNb() + 1, $value, $flags);
  232. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $parsed instanceof \stdClass) {
  233. $parsed = (array) $parsed;
  234. }
  235. if (!\is_array($parsed)) {
  236. throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  237. }
  238. if (isset($parsed[0])) {
  239. // If the value associated with the merge key is a sequence, then this sequence is expected to contain mapping nodes
  240. // and each of these nodes is merged in turn according to its order in the sequence. Keys in mapping nodes earlier
  241. // in the sequence override keys specified in later mapping nodes.
  242. foreach ($parsed as $parsedItem) {
  243. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $parsedItem instanceof \stdClass) {
  244. $parsedItem = (array) $parsedItem;
  245. }
  246. if (!\is_array($parsedItem)) {
  247. throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem, $this->filename);
  248. }
  249. $data += $parsedItem; // array union
  250. }
  251. } else {
  252. // If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the
  253. // current mapping, unless the key already exists in it.
  254. $data += $parsed; // array union
  255. }
  256. }
  257. } elseif ('<<' !== $key && isset($values['value']) && '&' === $values['value'][0] && self::preg_match(self::REFERENCE_PATTERN, $values['value'], $matches)) {
  258. $isRef = $matches['ref'];
  259. $this->refsBeingParsed[] = $isRef;
  260. $values['value'] = $matches['value'];
  261. }
  262. $subTag = null;
  263. if ($mergeNode) {
  264. // Merge keys
  265. } elseif (!isset($values['value']) || '' === $values['value'] || 0 === strpos($values['value'], '#') || (null !== $subTag = $this->getLineTag($values['value'], $flags)) || '<<' === $key) {
  266. // hash
  267. // if next line is less indented or equal, then it means that the current value is null
  268. if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) {
  269. // Spec: Keys MUST be unique; first one wins.
  270. // But overwriting is allowed when a merge node is used in current block.
  271. if ($allowOverwrite || !isset($data[$key])) {
  272. if (null !== $subTag) {
  273. $data[$key] = new TaggedValue($subTag, '');
  274. } else {
  275. $data[$key] = null;
  276. }
  277. } else {
  278. throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), $this->getRealCurrentLineNb() + 1, $this->currentLine);
  279. }
  280. } else {
  281. // remember the parsed line number here in case we need it to provide some contexts in error messages below
  282. $realCurrentLineNbKey = $this->getRealCurrentLineNb();
  283. $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $flags);
  284. if ('<<' === $key) {
  285. $this->refs[$refMatches['ref']] = $value;
  286. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $value instanceof \stdClass) {
  287. $value = (array) $value;
  288. }
  289. $data += $value;
  290. } elseif ($allowOverwrite || !isset($data[$key])) {
  291. // Spec: Keys MUST be unique; first one wins.
  292. // But overwriting is allowed when a merge node is used in current block.
  293. if (null !== $subTag) {
  294. $data[$key] = new TaggedValue($subTag, $value);
  295. } else {
  296. $data[$key] = $value;
  297. }
  298. } else {
  299. throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), $realCurrentLineNbKey + 1, $this->currentLine);
  300. }
  301. }
  302. } else {
  303. $value = $this->parseValue(rtrim($values['value']), $flags, $context);
  304. // Spec: Keys MUST be unique; first one wins.
  305. // But overwriting is allowed when a merge node is used in current block.
  306. if ($allowOverwrite || !isset($data[$key])) {
  307. $data[$key] = $value;
  308. } else {
  309. throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), $this->getRealCurrentLineNb() + 1, $this->currentLine);
  310. }
  311. }
  312. if ($isRef) {
  313. $this->refs[$isRef] = $data[$key];
  314. array_pop($this->refsBeingParsed);
  315. }
  316. } elseif ('"' === $this->currentLine[0] || "'" === $this->currentLine[0]) {
  317. if (null !== $context) {
  318. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  319. }
  320. try {
  321. return Inline::parse($this->lexInlineQuotedString(), $flags, $this->refs);
  322. } catch (ParseException $e) {
  323. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  324. $e->setSnippet($this->currentLine);
  325. throw $e;
  326. }
  327. } elseif ('{' === $this->currentLine[0]) {
  328. if (null !== $context) {
  329. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  330. }
  331. try {
  332. $parsedMapping = Inline::parse($this->lexInlineMapping(), $flags, $this->refs);
  333. while ($this->moveToNextLine()) {
  334. if (!$this->isCurrentLineEmpty()) {
  335. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  336. }
  337. }
  338. return $parsedMapping;
  339. } catch (ParseException $e) {
  340. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  341. $e->setSnippet($this->currentLine);
  342. throw $e;
  343. }
  344. } elseif ('[' === $this->currentLine[0]) {
  345. if (null !== $context) {
  346. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  347. }
  348. try {
  349. $parsedSequence = Inline::parse($this->lexInlineSequence(), $flags, $this->refs);
  350. while ($this->moveToNextLine()) {
  351. if (!$this->isCurrentLineEmpty()) {
  352. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  353. }
  354. }
  355. return $parsedSequence;
  356. } catch (ParseException $e) {
  357. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  358. $e->setSnippet($this->currentLine);
  359. throw $e;
  360. }
  361. } else {
  362. // multiple documents are not supported
  363. if ('---' === $this->currentLine) {
  364. throw new ParseException('Multiple documents are not supported.', $this->currentLineNb + 1, $this->currentLine, $this->filename);
  365. }
  366. if ($deprecatedUsage = (isset($this->currentLine[1]) && '?' === $this->currentLine[0] && ' ' === $this->currentLine[1])) {
  367. throw new ParseException('Complex mappings are not supported.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  368. }
  369. // 1-liner optionally followed by newline(s)
  370. if (\is_string($value) && $this->lines[0] === trim($value)) {
  371. try {
  372. $value = Inline::parse($this->lines[0], $flags, $this->refs);
  373. } catch (ParseException $e) {
  374. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  375. $e->setSnippet($this->currentLine);
  376. throw $e;
  377. }
  378. return $value;
  379. }
  380. // try to parse the value as a multi-line string as a last resort
  381. if (0 === $this->currentLineNb) {
  382. $previousLineWasNewline = false;
  383. $previousLineWasTerminatedWithBackslash = false;
  384. $value = '';
  385. foreach ($this->lines as $line) {
  386. $trimmedLine = trim($line);
  387. if ('#' === ($trimmedLine[0] ?? '')) {
  388. continue;
  389. }
  390. // If the indentation is not consistent at offset 0, it is to be considered as a ParseError
  391. if (0 === $this->offset && !$deprecatedUsage && isset($line[0]) && ' ' === $line[0]) {
  392. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  393. }
  394. if (false !== strpos($line, ': ')) {
  395. throw new ParseException('Mapping values are not allowed in multi-line blocks.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  396. }
  397. if ('' === $trimmedLine) {
  398. $value .= "\n";
  399. } elseif (!$previousLineWasNewline && !$previousLineWasTerminatedWithBackslash) {
  400. $value .= ' ';
  401. }
  402. if ('' !== $trimmedLine && '\\' === substr($line, -1)) {
  403. $value .= ltrim(substr($line, 0, -1));
  404. } elseif ('' !== $trimmedLine) {
  405. $value .= $trimmedLine;
  406. }
  407. if ('' === $trimmedLine) {
  408. $previousLineWasNewline = true;
  409. $previousLineWasTerminatedWithBackslash = false;
  410. } elseif ('\\' === substr($line, -1)) {
  411. $previousLineWasNewline = false;
  412. $previousLineWasTerminatedWithBackslash = true;
  413. } else {
  414. $previousLineWasNewline = false;
  415. $previousLineWasTerminatedWithBackslash = false;
  416. }
  417. }
  418. try {
  419. return Inline::parse(trim($value));
  420. } catch (ParseException $e) {
  421. // fall-through to the ParseException thrown below
  422. }
  423. }
  424. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  425. }
  426. } while ($this->moveToNextLine());
  427. if (null !== $tag) {
  428. $data = new TaggedValue($tag, $data);
  429. }
  430. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && 'mapping' === $context && !\is_object($data)) {
  431. $object = new \stdClass();
  432. foreach ($data as $key => $value) {
  433. $object->$key = $value;
  434. }
  435. $data = $object;
  436. }
  437. return empty($data) ? null : $data;
  438. }
  439. private function parseBlock(int $offset, string $yaml, int $flags)
  440. {
  441. $skippedLineNumbers = $this->skippedLineNumbers;
  442. foreach ($this->locallySkippedLineNumbers as $lineNumber) {
  443. if ($lineNumber < $offset) {
  444. continue;
  445. }
  446. $skippedLineNumbers[] = $lineNumber;
  447. }
  448. $parser = new self();
  449. $parser->offset = $offset;
  450. $parser->totalNumberOfLines = $this->totalNumberOfLines;
  451. $parser->skippedLineNumbers = $skippedLineNumbers;
  452. $parser->refs = &$this->refs;
  453. $parser->refsBeingParsed = $this->refsBeingParsed;
  454. return $parser->doParse($yaml, $flags);
  455. }
  456. /**
  457. * Returns the current line number (takes the offset into account).
  458. *
  459. * @internal
  460. *
  461. * @return int The current line number
  462. */
  463. public function getRealCurrentLineNb(): int
  464. {
  465. $realCurrentLineNumber = $this->currentLineNb + $this->offset;
  466. foreach ($this->skippedLineNumbers as $skippedLineNumber) {
  467. if ($skippedLineNumber > $realCurrentLineNumber) {
  468. break;
  469. }
  470. ++$realCurrentLineNumber;
  471. }
  472. return $realCurrentLineNumber;
  473. }
  474. /**
  475. * Returns the current line indentation.
  476. *
  477. * @return int The current line indentation
  478. */
  479. private function getCurrentLineIndentation(): int
  480. {
  481. if (' ' !== ($this->currentLine[0] ?? '')) {
  482. return 0;
  483. }
  484. return \strlen($this->currentLine) - \strlen(ltrim($this->currentLine, ' '));
  485. }
  486. /**
  487. * Returns the next embed block of YAML.
  488. *
  489. * @param int|null $indentation The indent level at which the block is to be read, or null for default
  490. * @param bool $inSequence True if the enclosing data structure is a sequence
  491. *
  492. * @return string A YAML string
  493. *
  494. * @throws ParseException When indentation problem are detected
  495. */
  496. private function getNextEmbedBlock(int $indentation = null, bool $inSequence = false): string
  497. {
  498. $oldLineIndentation = $this->getCurrentLineIndentation();
  499. if (!$this->moveToNextLine()) {
  500. return '';
  501. }
  502. if (null === $indentation) {
  503. $newIndent = null;
  504. $movements = 0;
  505. do {
  506. $EOF = false;
  507. // empty and comment-like lines do not influence the indentation depth
  508. if ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) {
  509. $EOF = !$this->moveToNextLine();
  510. if (!$EOF) {
  511. ++$movements;
  512. }
  513. } else {
  514. $newIndent = $this->getCurrentLineIndentation();
  515. }
  516. } while (!$EOF && null === $newIndent);
  517. for ($i = 0; $i < $movements; ++$i) {
  518. $this->moveToPreviousLine();
  519. }
  520. $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem();
  521. if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
  522. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  523. }
  524. } else {
  525. $newIndent = $indentation;
  526. }
  527. $data = [];
  528. if ($this->getCurrentLineIndentation() >= $newIndent) {
  529. $data[] = substr($this->currentLine, $newIndent ?? 0);
  530. } elseif ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) {
  531. $data[] = $this->currentLine;
  532. } else {
  533. $this->moveToPreviousLine();
  534. return '';
  535. }
  536. if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) {
  537. // the previous line contained a dash but no item content, this line is a sequence item with the same indentation
  538. // and therefore no nested list or mapping
  539. $this->moveToPreviousLine();
  540. return '';
  541. }
  542. $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
  543. $isItComment = $this->isCurrentLineComment();
  544. while ($this->moveToNextLine()) {
  545. if ($isItComment && !$isItUnindentedCollection) {
  546. $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
  547. $isItComment = $this->isCurrentLineComment();
  548. }
  549. $indent = $this->getCurrentLineIndentation();
  550. if ($isItUnindentedCollection && !$this->isCurrentLineEmpty() && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) {
  551. $this->moveToPreviousLine();
  552. break;
  553. }
  554. if ($this->isCurrentLineBlank()) {
  555. $data[] = substr($this->currentLine, $newIndent);
  556. continue;
  557. }
  558. if ($indent >= $newIndent) {
  559. $data[] = substr($this->currentLine, $newIndent);
  560. } elseif ($this->isCurrentLineComment()) {
  561. $data[] = $this->currentLine;
  562. } elseif (0 == $indent) {
  563. $this->moveToPreviousLine();
  564. break;
  565. } else {
  566. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  567. }
  568. }
  569. return implode("\n", $data);
  570. }
  571. private function hasMoreLines(): bool
  572. {
  573. return (\count($this->lines) - 1) > $this->currentLineNb;
  574. }
  575. /**
  576. * Moves the parser to the next line.
  577. */
  578. private function moveToNextLine(): bool
  579. {
  580. if ($this->currentLineNb >= $this->numberOfParsedLines - 1) {
  581. return false;
  582. }
  583. $this->currentLine = $this->lines[++$this->currentLineNb];
  584. return true;
  585. }
  586. /**
  587. * Moves the parser to the previous line.
  588. */
  589. private function moveToPreviousLine(): bool
  590. {
  591. if ($this->currentLineNb < 1) {
  592. return false;
  593. }
  594. $this->currentLine = $this->lines[--$this->currentLineNb];
  595. return true;
  596. }
  597. /**
  598. * Parses a YAML value.
  599. *
  600. * @param string $value A YAML value
  601. * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
  602. * @param string $context The parser context (either sequence or mapping)
  603. *
  604. * @return mixed A PHP value
  605. *
  606. * @throws ParseException When reference does not exist
  607. */
  608. private function parseValue(string $value, int $flags, string $context)
  609. {
  610. if (0 === strpos($value, '*')) {
  611. if (false !== $pos = strpos($value, '#')) {
  612. $value = substr($value, 1, $pos - 2);
  613. } else {
  614. $value = substr($value, 1);
  615. }
  616. if (!\array_key_exists($value, $this->refs)) {
  617. if (false !== $pos = array_search($value, $this->refsBeingParsed, true)) {
  618. throw new ParseException(sprintf('Circular reference [%s] detected for reference "%s".', implode(', ', array_merge(\array_slice($this->refsBeingParsed, $pos), [$value])), $value), $this->currentLineNb + 1, $this->currentLine, $this->filename);
  619. }
  620. throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine, $this->filename);
  621. }
  622. return $this->refs[$value];
  623. }
  624. if (\in_array($value[0], ['!', '|', '>'], true) && self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
  625. $modifiers = $matches['modifiers'] ?? '';
  626. $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), abs((int) $modifiers));
  627. if ('' !== $matches['tag'] && '!' !== $matches['tag']) {
  628. if ('!!binary' === $matches['tag']) {
  629. return Inline::evaluateBinaryScalar($data);
  630. }
  631. return new TaggedValue(substr($matches['tag'], 1), $data);
  632. }
  633. return $data;
  634. }
  635. try {
  636. if ('' !== $value && '{' === $value[0]) {
  637. $cursor = \strlen(rtrim($this->currentLine)) - \strlen(rtrim($value));
  638. return Inline::parse($this->lexInlineMapping($cursor), $flags, $this->refs);
  639. } elseif ('' !== $value && '[' === $value[0]) {
  640. $cursor = \strlen(rtrim($this->currentLine)) - \strlen(rtrim($value));
  641. return Inline::parse($this->lexInlineSequence($cursor), $flags, $this->refs);
  642. }
  643. switch ($value[0] ?? '') {
  644. case '"':
  645. case "'":
  646. $cursor = \strlen(rtrim($this->currentLine)) - \strlen(rtrim($value));
  647. $parsedValue = Inline::parse($this->lexInlineQuotedString($cursor), $flags, $this->refs);
  648. if (isset($this->currentLine[$cursor]) && preg_replace('/\s*(#.*)?$/A', '', substr($this->currentLine, $cursor))) {
  649. throw new ParseException(sprintf('Unexpected characters near "%s".', substr($this->currentLine, $cursor)));
  650. }
  651. return $parsedValue;
  652. default:
  653. $lines = [];
  654. while ($this->moveToNextLine()) {
  655. // unquoted strings end before the first unindented line
  656. if (0 === $this->getCurrentLineIndentation()) {
  657. $this->moveToPreviousLine();
  658. break;
  659. }
  660. $lines[] = trim($this->currentLine);
  661. }
  662. for ($i = 0, $linesCount = \count($lines), $previousLineBlank = false; $i < $linesCount; ++$i) {
  663. if ('' === $lines[$i]) {
  664. $value .= "\n";
  665. $previousLineBlank = true;
  666. } elseif ($previousLineBlank) {
  667. $value .= $lines[$i];
  668. $previousLineBlank = false;
  669. } else {
  670. $value .= ' '.$lines[$i];
  671. $previousLineBlank = false;
  672. }
  673. }
  674. Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
  675. $parsedValue = Inline::parse($value, $flags, $this->refs);
  676. if ('mapping' === $context && \is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
  677. throw new ParseException('A colon cannot be used in an unquoted mapping value.', $this->getRealCurrentLineNb() + 1, $value, $this->filename);
  678. }
  679. return $parsedValue;
  680. }
  681. } catch (ParseException $e) {
  682. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  683. $e->setSnippet($this->currentLine);
  684. throw $e;
  685. }
  686. }
  687. /**
  688. * Parses a block scalar.
  689. *
  690. * @param string $style The style indicator that was used to begin this block scalar (| or >)
  691. * @param string $chomping The chomping indicator that was used to begin this block scalar (+ or -)
  692. * @param int $indentation The indentation indicator that was used to begin this block scalar
  693. */
  694. private function parseBlockScalar(string $style, string $chomping = '', int $indentation = 0): string
  695. {
  696. $notEOF = $this->moveToNextLine();
  697. if (!$notEOF) {
  698. return '';
  699. }
  700. $isCurrentLineBlank = $this->isCurrentLineBlank();
  701. $blockLines = [];
  702. // leading blank lines are consumed before determining indentation
  703. while ($notEOF && $isCurrentLineBlank) {
  704. // newline only if not EOF
  705. if ($notEOF = $this->moveToNextLine()) {
  706. $blockLines[] = '';
  707. $isCurrentLineBlank = $this->isCurrentLineBlank();
  708. }
  709. }
  710. // determine indentation if not specified
  711. if (0 === $indentation) {
  712. $currentLineLength = \strlen($this->currentLine);
  713. for ($i = 0; $i < $currentLineLength && ' ' === $this->currentLine[$i]; ++$i) {
  714. ++$indentation;
  715. }
  716. }
  717. if ($indentation > 0) {
  718. $pattern = sprintf('/^ {%d}(.*)$/', $indentation);
  719. while (
  720. $notEOF && (
  721. $isCurrentLineBlank ||
  722. self::preg_match($pattern, $this->currentLine, $matches)
  723. )
  724. ) {
  725. if ($isCurrentLineBlank && \strlen($this->currentLine) > $indentation) {
  726. $blockLines[] = substr($this->currentLine, $indentation);
  727. } elseif ($isCurrentLineBlank) {
  728. $blockLines[] = '';
  729. } else {
  730. $blockLines[] = $matches[1];
  731. }
  732. // newline only if not EOF
  733. if ($notEOF = $this->moveToNextLine()) {
  734. $isCurrentLineBlank = $this->isCurrentLineBlank();
  735. }
  736. }
  737. } elseif ($notEOF) {
  738. $blockLines[] = '';
  739. }
  740. if ($notEOF) {
  741. $blockLines[] = '';
  742. $this->moveToPreviousLine();
  743. } elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) {
  744. $blockLines[] = '';
  745. }
  746. // folded style
  747. if ('>' === $style) {
  748. $text = '';
  749. $previousLineIndented = false;
  750. $previousLineBlank = false;
  751. for ($i = 0, $blockLinesCount = \count($blockLines); $i < $blockLinesCount; ++$i) {
  752. if ('' === $blockLines[$i]) {
  753. $text .= "\n";
  754. $previousLineIndented = false;
  755. $previousLineBlank = true;
  756. } elseif (' ' === $blockLines[$i][0]) {
  757. $text .= "\n".$blockLines[$i];
  758. $previousLineIndented = true;
  759. $previousLineBlank = false;
  760. } elseif ($previousLineIndented) {
  761. $text .= "\n".$blockLines[$i];
  762. $previousLineIndented = false;
  763. $previousLineBlank = false;
  764. } elseif ($previousLineBlank || 0 === $i) {
  765. $text .= $blockLines[$i];
  766. $previousLineIndented = false;
  767. $previousLineBlank = false;
  768. } else {
  769. $text .= ' '.$blockLines[$i];
  770. $previousLineIndented = false;
  771. $previousLineBlank = false;
  772. }
  773. }
  774. } else {
  775. $text = implode("\n", $blockLines);
  776. }
  777. // deal with trailing newlines
  778. if ('' === $chomping) {
  779. $text = preg_replace('/\n+$/', "\n", $text);
  780. } elseif ('-' === $chomping) {
  781. $text = preg_replace('/\n+$/', '', $text);
  782. }
  783. return $text;
  784. }
  785. /**
  786. * Returns true if the next line is indented.
  787. *
  788. * @return bool Returns true if the next line is indented, false otherwise
  789. */
  790. private function isNextLineIndented(): bool
  791. {
  792. $currentIndentation = $this->getCurrentLineIndentation();
  793. $movements = 0;
  794. do {
  795. $EOF = !$this->moveToNextLine();
  796. if (!$EOF) {
  797. ++$movements;
  798. }
  799. } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
  800. if ($EOF) {
  801. return false;
  802. }
  803. $ret = $this->getCurrentLineIndentation() > $currentIndentation;
  804. for ($i = 0; $i < $movements; ++$i) {
  805. $this->moveToPreviousLine();
  806. }
  807. return $ret;
  808. }
  809. /**
  810. * Returns true if the current line is blank or if it is a comment line.
  811. *
  812. * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise
  813. */
  814. private function isCurrentLineEmpty(): bool
  815. {
  816. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  817. }
  818. /**
  819. * Returns true if the current line is blank.
  820. *
  821. * @return bool Returns true if the current line is blank, false otherwise
  822. */
  823. private function isCurrentLineBlank(): bool
  824. {
  825. return '' === $this->currentLine || '' === trim($this->currentLine, ' ');
  826. }
  827. /**
  828. * Returns true if the current line is a comment line.
  829. *
  830. * @return bool Returns true if the current line is a comment line, false otherwise
  831. */
  832. private function isCurrentLineComment(): bool
  833. {
  834. //checking explicitly the first char of the trim is faster than loops or strpos
  835. $ltrimmedLine = '' !== $this->currentLine && ' ' === $this->currentLine[0] ? ltrim($this->currentLine, ' ') : $this->currentLine;
  836. return '' !== $ltrimmedLine && '#' === $ltrimmedLine[0];
  837. }
  838. private function isCurrentLineLastLineInDocument(): bool
  839. {
  840. return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1);
  841. }
  842. /**
  843. * Cleanups a YAML string to be parsed.
  844. *
  845. * @param string $value The input YAML string
  846. *
  847. * @return string A cleaned up YAML string
  848. */
  849. private function cleanup(string $value): string
  850. {
  851. $value = str_replace(["\r\n", "\r"], "\n", $value);
  852. // strip YAML header
  853. $count = 0;
  854. $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
  855. $this->offset += $count;
  856. // remove leading comments
  857. $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
  858. if (1 === $count) {
  859. // items have been removed, update the offset
  860. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  861. $value = $trimmedValue;
  862. }
  863. // remove start of the document marker (---)
  864. $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
  865. if (1 === $count) {
  866. // items have been removed, update the offset
  867. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  868. $value = $trimmedValue;
  869. // remove end of the document marker (...)
  870. $value = preg_replace('#\.\.\.\s*$#', '', $value);
  871. }
  872. return $value;
  873. }
  874. /**
  875. * Returns true if the next line starts unindented collection.
  876. *
  877. * @return bool Returns true if the next line starts unindented collection, false otherwise
  878. */
  879. private function isNextLineUnIndentedCollection(): bool
  880. {
  881. $currentIndentation = $this->getCurrentLineIndentation();
  882. $movements = 0;
  883. do {
  884. $EOF = !$this->moveToNextLine();
  885. if (!$EOF) {
  886. ++$movements;
  887. }
  888. } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
  889. if ($EOF) {
  890. return false;
  891. }
  892. $ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem();
  893. for ($i = 0; $i < $movements; ++$i) {
  894. $this->moveToPreviousLine();
  895. }
  896. return $ret;
  897. }
  898. /**
  899. * Returns true if the string is un-indented collection item.
  900. *
  901. * @return bool Returns true if the string is un-indented collection item, false otherwise
  902. */
  903. private function isStringUnIndentedCollectionItem(): bool
  904. {
  905. return '-' === rtrim($this->currentLine) || 0 === strpos($this->currentLine, '- ');
  906. }
  907. /**
  908. * A local wrapper for "preg_match" which will throw a ParseException if there
  909. * is an internal error in the PCRE engine.
  910. *
  911. * This avoids us needing to check for "false" every time PCRE is used
  912. * in the YAML engine
  913. *
  914. * @throws ParseException on a PCRE internal error
  915. *
  916. * @see preg_last_error()
  917. *
  918. * @internal
  919. */
  920. public static function preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int
  921. {
  922. if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) {
  923. switch (preg_last_error()) {
  924. case \PREG_INTERNAL_ERROR:
  925. $error = 'Internal PCRE error.';
  926. break;
  927. case \PREG_BACKTRACK_LIMIT_ERROR:
  928. $error = 'pcre.backtrack_limit reached.';
  929. break;
  930. case \PREG_RECURSION_LIMIT_ERROR:
  931. $error = 'pcre.recursion_limit reached.';
  932. break;
  933. case \PREG_BAD_UTF8_ERROR:
  934. $error = 'Malformed UTF-8 data.';
  935. break;
  936. case \PREG_BAD_UTF8_OFFSET_ERROR:
  937. $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
  938. break;
  939. default:
  940. $error = 'Error.';
  941. }
  942. throw new ParseException($error);
  943. }
  944. return $ret;
  945. }
  946. /**
  947. * Trim the tag on top of the value.
  948. *
  949. * Prevent values such as "!foo {quz: bar}" to be considered as
  950. * a mapping block.
  951. */
  952. private function trimTag(string $value): string
  953. {
  954. if ('!' === $value[0]) {
  955. return ltrim(substr($value, 1, strcspn($value, " \r\n", 1)), ' ');
  956. }
  957. return $value;
  958. }
  959. private function getLineTag(string $value, int $flags, bool $nextLineCheck = true): ?string
  960. {
  961. if ('' === $value || '!' !== $value[0] || 1 !== self::preg_match('/^'.self::TAG_PATTERN.' *( +#.*)?$/', $value, $matches)) {
  962. return null;
  963. }
  964. if ($nextLineCheck && !$this->isNextLineIndented()) {
  965. return null;
  966. }
  967. $tag = substr($matches['tag'], 1);
  968. // Built-in tags
  969. if ($tag && '!' === $tag[0]) {
  970. throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag), $this->getRealCurrentLineNb() + 1, $value, $this->filename);
  971. }
  972. if (Yaml::PARSE_CUSTOM_TAGS & $flags) {
  973. return $tag;
  974. }
  975. throw new ParseException(sprintf('Tags support is not enabled. You must use the flag "Yaml::PARSE_CUSTOM_TAGS" to use "%s".', $matches['tag']), $this->getRealCurrentLineNb() + 1, $value, $this->filename);
  976. }
  977. private function lexInlineQuotedString(int &$cursor = 0): string
  978. {
  979. $quotation = $this->currentLine[$cursor];
  980. $value = $quotation;
  981. ++$cursor;
  982. $previousLineWasNewline = true;
  983. $previousLineWasTerminatedWithBackslash = false;
  984. $lineNumber = 0;
  985. do {
  986. if (++$lineNumber > 1) {
  987. $cursor += strspn($this->currentLine, ' ', $cursor);
  988. }
  989. if ($this->isCurrentLineBlank()) {
  990. $value .= "\n";
  991. } elseif (!$previousLineWasNewline && !$previousLineWasTerminatedWithBackslash) {
  992. $value .= ' ';
  993. }
  994. for (; \strlen($this->currentLine) > $cursor; ++$cursor) {
  995. switch ($this->currentLine[$cursor]) {
  996. case '\\':
  997. if ("'" === $quotation) {
  998. $value .= '\\';
  999. } elseif (isset($this->currentLine[++$cursor])) {
  1000. $value .= '\\'.$this->currentLine[$cursor];
  1001. }
  1002. break;
  1003. case $quotation:
  1004. ++$cursor;
  1005. if ("'" === $quotation && isset($this->currentLine[$cursor]) && "'" === $this->currentLine[$cursor]) {
  1006. $value .= "''";
  1007. break;
  1008. }
  1009. return $value.$quotation;
  1010. default:
  1011. $value .= $this->currentLine[$cursor];
  1012. }
  1013. }
  1014. if ($this->isCurrentLineBlank()) {
  1015. $previousLineWasNewline = true;
  1016. $previousLineWasTerminatedWithBackslash = false;
  1017. } elseif ('\\' === $this->currentLine[-1]) {
  1018. $previousLineWasNewline = false;
  1019. $previousLineWasTerminatedWithBackslash = true;
  1020. } else {
  1021. $previousLineWasNewline = false;
  1022. $previousLineWasTerminatedWithBackslash = false;
  1023. }
  1024. if ($this->hasMoreLines()) {
  1025. $cursor = 0;
  1026. }
  1027. } while ($this->moveToNextLine());
  1028. throw new ParseException('Malformed inline YAML string.');
  1029. }
  1030. private function lexUnquotedString(int &$cursor): string
  1031. {
  1032. $offset = $cursor;
  1033. $cursor += strcspn($this->currentLine, '[]{},: ', $cursor);
  1034. if ($cursor === $offset) {
  1035. throw new ParseException('Malformed unquoted YAML string.');
  1036. }
  1037. return substr($this->currentLine, $offset, $cursor - $offset);
  1038. }
  1039. private function lexInlineMapping(int &$cursor = 0): string
  1040. {
  1041. return $this->lexInlineStructure($cursor, '}');
  1042. }
  1043. private function lexInlineSequence(int &$cursor = 0): string
  1044. {
  1045. return $this->lexInlineStructure($cursor, ']');
  1046. }
  1047. private function lexInlineStructure(int &$cursor, string $closingTag): string
  1048. {
  1049. $value = $this->currentLine[$cursor];
  1050. ++$cursor;
  1051. do {
  1052. $this->consumeWhitespaces($cursor);
  1053. while (isset($this->currentLine[$cursor])) {
  1054. switch ($this->currentLine[$cursor]) {
  1055. case '"':
  1056. case "'":
  1057. $value .= $this->lexInlineQuotedString($cursor);
  1058. break;
  1059. case ':':
  1060. case ',':
  1061. $value .= $this->currentLine[$cursor];
  1062. ++$cursor;
  1063. break;
  1064. case '{':
  1065. $value .= $this->lexInlineMapping($cursor);
  1066. break;
  1067. case '[':
  1068. $value .= $this->lexInlineSequence($cursor);
  1069. break;
  1070. case $closingTag:
  1071. $value .= $this->currentLine[$cursor];
  1072. ++$cursor;
  1073. return $value;
  1074. case '#':
  1075. break 2;
  1076. default:
  1077. $value .= $this->lexUnquotedString($cursor);
  1078. }
  1079. if ($this->consumeWhitespaces($cursor)) {
  1080. $value .= ' ';
  1081. }
  1082. }
  1083. if ($this->hasMoreLines()) {
  1084. $cursor = 0;
  1085. }
  1086. } while ($this->moveToNextLine());
  1087. throw new ParseException('Malformed inline YAML string.');
  1088. }
  1089. private function consumeWhitespaces(int &$cursor): bool
  1090. {
  1091. $whitespacesConsumed = 0;
  1092. do {
  1093. $whitespaceOnlyTokenLength = strspn($this->currentLine, ' ', $cursor);
  1094. $whitespacesConsumed += $whitespaceOnlyTokenLength;
  1095. $cursor += $whitespaceOnlyTokenLength;
  1096. if (isset($this->currentLine[$cursor])) {
  1097. return 0 < $whitespacesConsumed;
  1098. }
  1099. if ($this->hasMoreLines()) {
  1100. $cursor = 0;
  1101. }
  1102. } while ($this->moveToNextLine());
  1103. return 0 < $whitespacesConsumed;
  1104. }
  1105. }