Parser.php 50 KB

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