Parser.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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], ['"', "'"]))
  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. $lines[] = trim($this->currentLine);
  646. }
  647. for ($i = 0, $linesCount = \count($lines), $previousLineBlank = false; $i < $linesCount; ++$i) {
  648. if ('' === $lines[$i]) {
  649. $value .= "\n";
  650. $previousLineBlank = true;
  651. } elseif ($previousLineBlank) {
  652. $value .= $lines[$i];
  653. $previousLineBlank = false;
  654. } else {
  655. $value .= ' '.$lines[$i];
  656. $previousLineBlank = false;
  657. }
  658. }
  659. Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
  660. $parsedValue = Inline::parse($value, $flags, $this->refs);
  661. if ('mapping' === $context && \is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && str_contains($parsedValue, ': ')) {
  662. throw new ParseException('A colon cannot be used in an unquoted mapping value.', $this->getRealCurrentLineNb() + 1, $value, $this->filename);
  663. }
  664. return $parsedValue;
  665. }
  666. } catch (ParseException $e) {
  667. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  668. $e->setSnippet($this->currentLine);
  669. throw $e;
  670. }
  671. }
  672. /**
  673. * Parses a block scalar.
  674. *
  675. * @param string $style The style indicator that was used to begin this block scalar (| or >)
  676. * @param string $chomping The chomping indicator that was used to begin this block scalar (+ or -)
  677. * @param int $indentation The indentation indicator that was used to begin this block scalar
  678. */
  679. private function parseBlockScalar(string $style, string $chomping = '', int $indentation = 0): string
  680. {
  681. $notEOF = $this->moveToNextLine();
  682. if (!$notEOF) {
  683. return '';
  684. }
  685. $isCurrentLineBlank = $this->isCurrentLineBlank();
  686. $blockLines = [];
  687. // leading blank lines are consumed before determining indentation
  688. while ($notEOF && $isCurrentLineBlank) {
  689. // newline only if not EOF
  690. if ($notEOF = $this->moveToNextLine()) {
  691. $blockLines[] = '';
  692. $isCurrentLineBlank = $this->isCurrentLineBlank();
  693. }
  694. }
  695. // determine indentation if not specified
  696. if (0 === $indentation) {
  697. $currentLineLength = \strlen($this->currentLine);
  698. for ($i = 0; $i < $currentLineLength && ' ' === $this->currentLine[$i]; ++$i) {
  699. ++$indentation;
  700. }
  701. }
  702. if ($indentation > 0) {
  703. $pattern = \sprintf('/^ {%d}(.*)$/', $indentation);
  704. while (
  705. $notEOF && (
  706. $isCurrentLineBlank
  707. || self::preg_match($pattern, $this->currentLine, $matches)
  708. )
  709. ) {
  710. if ($isCurrentLineBlank && \strlen($this->currentLine) > $indentation) {
  711. $blockLines[] = substr($this->currentLine, $indentation);
  712. } elseif ($isCurrentLineBlank) {
  713. $blockLines[] = '';
  714. } else {
  715. $blockLines[] = $matches[1];
  716. }
  717. // newline only if not EOF
  718. if ($notEOF = $this->moveToNextLine()) {
  719. $isCurrentLineBlank = $this->isCurrentLineBlank();
  720. }
  721. }
  722. } elseif ($notEOF) {
  723. $blockLines[] = '';
  724. }
  725. if ($notEOF) {
  726. $blockLines[] = '';
  727. $this->moveToPreviousLine();
  728. } elseif (!$this->isCurrentLineLastLineInDocument()) {
  729. $blockLines[] = '';
  730. }
  731. // folded style
  732. if ('>' === $style) {
  733. $text = '';
  734. $previousLineIndented = false;
  735. $previousLineBlank = false;
  736. for ($i = 0, $blockLinesCount = \count($blockLines); $i < $blockLinesCount; ++$i) {
  737. if ('' === $blockLines[$i]) {
  738. $text .= "\n";
  739. $previousLineIndented = false;
  740. $previousLineBlank = true;
  741. } elseif (' ' === $blockLines[$i][0]) {
  742. $text .= "\n".$blockLines[$i];
  743. $previousLineIndented = true;
  744. $previousLineBlank = false;
  745. } elseif ($previousLineIndented) {
  746. $text .= "\n".$blockLines[$i];
  747. $previousLineIndented = false;
  748. $previousLineBlank = false;
  749. } elseif ($previousLineBlank || 0 === $i) {
  750. $text .= $blockLines[$i];
  751. $previousLineIndented = false;
  752. $previousLineBlank = false;
  753. } else {
  754. $text .= ' '.$blockLines[$i];
  755. $previousLineIndented = false;
  756. $previousLineBlank = false;
  757. }
  758. }
  759. } else {
  760. $text = implode("\n", $blockLines);
  761. }
  762. // deal with trailing newlines
  763. if ('' === $chomping) {
  764. $text = preg_replace('/\n+$/', "\n", $text);
  765. } elseif ('-' === $chomping) {
  766. $text = preg_replace('/\n+$/', '', $text);
  767. }
  768. return $text;
  769. }
  770. /**
  771. * Returns true if the next line is indented.
  772. */
  773. private function isNextLineIndented(): bool
  774. {
  775. $currentIndentation = $this->getCurrentLineIndentation();
  776. $movements = 0;
  777. do {
  778. $EOF = !$this->moveToNextLine();
  779. if (!$EOF) {
  780. ++$movements;
  781. }
  782. } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
  783. if ($EOF) {
  784. for ($i = 0; $i < $movements; ++$i) {
  785. $this->moveToPreviousLine();
  786. }
  787. return false;
  788. }
  789. $ret = $this->getCurrentLineIndentation() > $currentIndentation;
  790. for ($i = 0; $i < $movements; ++$i) {
  791. $this->moveToPreviousLine();
  792. }
  793. return $ret;
  794. }
  795. private function isCurrentLineEmpty(): bool
  796. {
  797. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  798. }
  799. private function isCurrentLineBlank(): bool
  800. {
  801. return '' === $this->currentLine || '' === trim($this->currentLine, ' ');
  802. }
  803. private function isCurrentLineComment(): bool
  804. {
  805. // checking explicitly the first char of the trim is faster than loops or strpos
  806. $ltrimmedLine = '' !== $this->currentLine && ' ' === $this->currentLine[0] ? ltrim($this->currentLine, ' ') : $this->currentLine;
  807. return '' !== $ltrimmedLine && '#' === $ltrimmedLine[0];
  808. }
  809. private function isCurrentLineLastLineInDocument(): bool
  810. {
  811. return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1);
  812. }
  813. private function cleanup(string $value): string
  814. {
  815. $value = str_replace(["\r\n", "\r"], "\n", $value);
  816. // strip YAML header
  817. $count = 0;
  818. $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
  819. $this->offset += $count;
  820. // remove leading comments
  821. $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
  822. if (1 === $count) {
  823. // items have been removed, update the offset
  824. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  825. $value = $trimmedValue;
  826. }
  827. // remove start of the document marker (---)
  828. $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
  829. if (1 === $count) {
  830. // items have been removed, update the offset
  831. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  832. $value = $trimmedValue;
  833. // remove end of the document marker (...)
  834. $value = preg_replace('#\.\.\.\s*$#', '', $value);
  835. }
  836. return $value;
  837. }
  838. private function isNextLineUnIndentedCollection(): bool
  839. {
  840. $currentIndentation = $this->getCurrentLineIndentation();
  841. $movements = 0;
  842. do {
  843. $EOF = !$this->moveToNextLine();
  844. if (!$EOF) {
  845. ++$movements;
  846. }
  847. } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
  848. if ($EOF) {
  849. return false;
  850. }
  851. $ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem();
  852. for ($i = 0; $i < $movements; ++$i) {
  853. $this->moveToPreviousLine();
  854. }
  855. return $ret;
  856. }
  857. private function isStringUnIndentedCollectionItem(): bool
  858. {
  859. return '-' === rtrim($this->currentLine) || str_starts_with($this->currentLine, '- ');
  860. }
  861. /**
  862. * A local wrapper for "preg_match" which will throw a ParseException if there
  863. * is an internal error in the PCRE engine.
  864. *
  865. * This avoids us needing to check for "false" every time PCRE is used
  866. * in the YAML engine
  867. *
  868. * @throws ParseException on a PCRE internal error
  869. *
  870. * @internal
  871. */
  872. public static function preg_match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int
  873. {
  874. if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) {
  875. throw new ParseException(preg_last_error_msg());
  876. }
  877. return $ret;
  878. }
  879. /**
  880. * Trim the tag on top of the value.
  881. *
  882. * Prevent values such as "!foo {quz: bar}" to be considered as
  883. * a mapping block.
  884. */
  885. private function trimTag(string $value): string
  886. {
  887. if ('!' === $value[0]) {
  888. return ltrim(substr($value, 1, strcspn($value, " \r\n", 1)), ' ');
  889. }
  890. return $value;
  891. }
  892. private function getLineTag(string $value, int $flags, bool $nextLineCheck = true): ?string
  893. {
  894. if ('' === $value || '!' !== $value[0] || 1 !== self::preg_match('/^'.self::TAG_PATTERN.' *( +#.*)?$/', $value, $matches)) {
  895. return null;
  896. }
  897. if ($nextLineCheck && !$this->isNextLineIndented()) {
  898. return null;
  899. }
  900. $tag = substr($matches['tag'], 1);
  901. // Built-in tags
  902. if ($tag && '!' === $tag[0]) {
  903. throw new ParseException(\sprintf('The built-in tag "!%s" is not implemented.', $tag), $this->getRealCurrentLineNb() + 1, $value, $this->filename);
  904. }
  905. if (Yaml::PARSE_CUSTOM_TAGS & $flags) {
  906. return $tag;
  907. }
  908. 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);
  909. }
  910. private function lexInlineQuotedString(int &$cursor = 0): string
  911. {
  912. $quotation = $this->currentLine[$cursor];
  913. $value = $quotation;
  914. ++$cursor;
  915. $previousLineWasNewline = true;
  916. $previousLineWasTerminatedWithBackslash = false;
  917. $lineNumber = 0;
  918. do {
  919. if (++$lineNumber > 1) {
  920. $cursor += strspn($this->currentLine, ' ', $cursor);
  921. }
  922. if ($this->isCurrentLineBlank()) {
  923. $value .= "\n";
  924. } elseif (!$previousLineWasNewline && !$previousLineWasTerminatedWithBackslash) {
  925. $value .= ' ';
  926. }
  927. for (; \strlen($this->currentLine) > $cursor; ++$cursor) {
  928. switch ($this->currentLine[$cursor]) {
  929. case '\\':
  930. if ("'" === $quotation) {
  931. $value .= '\\';
  932. } elseif (isset($this->currentLine[++$cursor])) {
  933. $value .= '\\'.$this->currentLine[$cursor];
  934. }
  935. break;
  936. case $quotation:
  937. ++$cursor;
  938. if ("'" === $quotation && isset($this->currentLine[$cursor]) && "'" === $this->currentLine[$cursor]) {
  939. $value .= "''";
  940. break;
  941. }
  942. return $value.$quotation;
  943. default:
  944. $value .= $this->currentLine[$cursor];
  945. }
  946. }
  947. if ($this->isCurrentLineBlank()) {
  948. $previousLineWasNewline = true;
  949. $previousLineWasTerminatedWithBackslash = false;
  950. } elseif ('\\' === $this->currentLine[-1]) {
  951. $previousLineWasNewline = false;
  952. $previousLineWasTerminatedWithBackslash = true;
  953. } else {
  954. $previousLineWasNewline = false;
  955. $previousLineWasTerminatedWithBackslash = false;
  956. }
  957. if ($this->hasMoreLines()) {
  958. $cursor = 0;
  959. }
  960. } while ($this->moveToNextLine());
  961. throw new ParseException('Malformed inline YAML string.');
  962. }
  963. private function lexUnquotedString(int &$cursor): string
  964. {
  965. $offset = $cursor;
  966. while ($cursor < \strlen($this->currentLine)) {
  967. if (\in_array($this->currentLine[$cursor], ['[', ']', '{', '}', ',', ':'], true)) {
  968. break;
  969. }
  970. if (\in_array($this->currentLine[$cursor], [' ', "\t"], true) && '#' === ($this->currentLine[$cursor + 1] ?? '')) {
  971. break;
  972. }
  973. ++$cursor;
  974. }
  975. if ($cursor === $offset) {
  976. throw new ParseException('Malformed unquoted YAML string.');
  977. }
  978. return substr($this->currentLine, $offset, $cursor - $offset);
  979. }
  980. private function lexInlineMapping(int &$cursor = 0, bool $consumeUntilEol = true): string
  981. {
  982. return $this->lexInlineStructure($cursor, '}', $consumeUntilEol);
  983. }
  984. private function lexInlineSequence(int &$cursor = 0, bool $consumeUntilEol = true): string
  985. {
  986. return $this->lexInlineStructure($cursor, ']', $consumeUntilEol);
  987. }
  988. private function lexInlineStructure(int &$cursor, string $closingTag, bool $consumeUntilEol = true): string
  989. {
  990. $value = $this->currentLine[$cursor];
  991. ++$cursor;
  992. do {
  993. $this->consumeWhitespaces($cursor);
  994. while (isset($this->currentLine[$cursor])) {
  995. switch ($this->currentLine[$cursor]) {
  996. case '"':
  997. case "'":
  998. $value .= $this->lexInlineQuotedString($cursor);
  999. break;
  1000. case ':':
  1001. case ',':
  1002. $value .= $this->currentLine[$cursor];
  1003. ++$cursor;
  1004. break;
  1005. case '{':
  1006. $value .= $this->lexInlineMapping($cursor, false);
  1007. break;
  1008. case '[':
  1009. $value .= $this->lexInlineSequence($cursor, false);
  1010. break;
  1011. case $closingTag:
  1012. $value .= $this->currentLine[$cursor];
  1013. ++$cursor;
  1014. if ($consumeUntilEol && isset($this->currentLine[$cursor]) && ($whitespaces = strspn($this->currentLine, ' ', $cursor) + $cursor) < \strlen($this->currentLine) && '#' !== $this->currentLine[$whitespaces]) {
  1015. throw new ParseException(\sprintf('Unexpected token "%s".', trim(substr($this->currentLine, $cursor))));
  1016. }
  1017. return $value;
  1018. case '#':
  1019. break 2;
  1020. default:
  1021. $value .= $this->lexUnquotedString($cursor);
  1022. }
  1023. if ($this->consumeWhitespaces($cursor)) {
  1024. $value .= ' ';
  1025. }
  1026. }
  1027. if ($this->hasMoreLines()) {
  1028. $cursor = 0;
  1029. }
  1030. } while ($this->moveToNextLine());
  1031. throw new ParseException('Malformed inline YAML string.');
  1032. }
  1033. private function consumeWhitespaces(int &$cursor): bool
  1034. {
  1035. $whitespacesConsumed = 0;
  1036. do {
  1037. $whitespaceOnlyTokenLength = strspn($this->currentLine, " \t", $cursor);
  1038. $whitespacesConsumed += $whitespaceOnlyTokenLength;
  1039. $cursor += $whitespaceOnlyTokenLength;
  1040. if (isset($this->currentLine[$cursor])) {
  1041. return 0 < $whitespacesConsumed;
  1042. }
  1043. if ($this->hasMoreLines()) {
  1044. $cursor = 0;
  1045. }
  1046. } while ($this->moveToNextLine());
  1047. return 0 < $whitespacesConsumed;
  1048. }
  1049. }