Parser.php 51 KB

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