Parser.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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 $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 $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 (null !== $subTag) {
  260. $data[$key] = new TaggedValue($subTag, '');
  261. } else {
  262. $data[$key] = null;
  263. }
  264. } else {
  265. throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), $this->getRealCurrentLineNb() + 1, $this->currentLine);
  266. }
  267. } else {
  268. // remember the parsed line number here in case we need it to provide some contexts in error messages below
  269. $realCurrentLineNbKey = $this->getRealCurrentLineNb();
  270. $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $flags);
  271. if ('<<' === $key) {
  272. $this->refs[$refMatches['ref']] = $value;
  273. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $value instanceof \stdClass) {
  274. $value = (array) $value;
  275. }
  276. $data += $value;
  277. } elseif ($allowOverwrite || !isset($data[$key])) {
  278. // Spec: Keys MUST be unique; first one wins.
  279. // But overwriting is allowed when a merge node is used in current block.
  280. if (null !== $subTag) {
  281. $data[$key] = new TaggedValue($subTag, $value);
  282. } else {
  283. $data[$key] = $value;
  284. }
  285. } else {
  286. throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), $realCurrentLineNbKey + 1, $this->currentLine);
  287. }
  288. }
  289. } else {
  290. $value = $this->parseValue(rtrim($values['value']), $flags, $context);
  291. // Spec: Keys MUST be unique; first one wins.
  292. // But overwriting is allowed when a merge node is used in current block.
  293. if ($allowOverwrite || !isset($data[$key])) {
  294. $data[$key] = $value;
  295. } else {
  296. throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), $this->getRealCurrentLineNb() + 1, $this->currentLine);
  297. }
  298. }
  299. if ($isRef) {
  300. $this->refs[$isRef] = $data[$key];
  301. array_pop($this->refsBeingParsed);
  302. }
  303. } elseif ('"' === $this->currentLine[0] || "'" === $this->currentLine[0]) {
  304. if (null !== $context) {
  305. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  306. }
  307. try {
  308. return Inline::parse($this->lexInlineQuotedString(), $flags, $this->refs);
  309. } catch (ParseException $e) {
  310. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  311. $e->setSnippet($this->currentLine);
  312. throw $e;
  313. }
  314. } elseif ('{' === $this->currentLine[0]) {
  315. if (null !== $context) {
  316. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  317. }
  318. try {
  319. $parsedMapping = Inline::parse($this->lexInlineMapping(), $flags, $this->refs);
  320. while ($this->moveToNextLine()) {
  321. if (!$this->isCurrentLineEmpty()) {
  322. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  323. }
  324. }
  325. return $parsedMapping;
  326. } catch (ParseException $e) {
  327. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  328. $e->setSnippet($this->currentLine);
  329. throw $e;
  330. }
  331. } elseif ('[' === $this->currentLine[0]) {
  332. if (null !== $context) {
  333. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  334. }
  335. try {
  336. $parsedSequence = Inline::parse($this->lexInlineSequence(), $flags, $this->refs);
  337. while ($this->moveToNextLine()) {
  338. if (!$this->isCurrentLineEmpty()) {
  339. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  340. }
  341. }
  342. return $parsedSequence;
  343. } catch (ParseException $e) {
  344. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  345. $e->setSnippet($this->currentLine);
  346. throw $e;
  347. }
  348. } else {
  349. // multiple documents are not supported
  350. if ('---' === $this->currentLine) {
  351. throw new ParseException('Multiple documents are not supported.', $this->currentLineNb + 1, $this->currentLine, $this->filename);
  352. }
  353. if (isset($this->currentLine[1]) && '?' === $this->currentLine[0] && ' ' === $this->currentLine[1]) {
  354. throw new ParseException('Complex mappings are not supported.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  355. }
  356. // 1-liner optionally followed by newline(s)
  357. if (\is_string($value) && $this->lines[0] === trim($value)) {
  358. try {
  359. $value = Inline::parse($this->lines[0], $flags, $this->refs);
  360. } catch (ParseException $e) {
  361. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  362. $e->setSnippet($this->currentLine);
  363. throw $e;
  364. }
  365. return $value;
  366. }
  367. // try to parse the value as a multi-line string as a last resort
  368. if (0 === $this->currentLineNb) {
  369. $previousLineWasNewline = false;
  370. $previousLineWasTerminatedWithBackslash = false;
  371. $value = '';
  372. foreach ($this->lines as $line) {
  373. $trimmedLine = trim($line);
  374. if ('#' === ($trimmedLine[0] ?? '')) {
  375. continue;
  376. }
  377. // If the indentation is not consistent at offset 0, it is to be considered as a ParseError
  378. if (0 === $this->offset && isset($line[0]) && ' ' === $line[0]) {
  379. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  380. }
  381. if (str_contains($line, ': ')) {
  382. throw new ParseException('Mapping values are not allowed in multi-line blocks.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  383. }
  384. if ('' === $trimmedLine) {
  385. $value .= "\n";
  386. } elseif (!$previousLineWasNewline && !$previousLineWasTerminatedWithBackslash) {
  387. $value .= ' ';
  388. }
  389. if ('' !== $trimmedLine && str_ends_with($line, '\\')) {
  390. $value .= ltrim(substr($line, 0, -1));
  391. } elseif ('' !== $trimmedLine) {
  392. $value .= $trimmedLine;
  393. }
  394. if ('' === $trimmedLine) {
  395. $previousLineWasNewline = true;
  396. $previousLineWasTerminatedWithBackslash = false;
  397. } elseif (str_ends_with($line, '\\')) {
  398. $previousLineWasNewline = false;
  399. $previousLineWasTerminatedWithBackslash = true;
  400. } else {
  401. $previousLineWasNewline = false;
  402. $previousLineWasTerminatedWithBackslash = false;
  403. }
  404. }
  405. try {
  406. return Inline::parse(trim($value));
  407. } catch (ParseException) {
  408. // fall-through to the ParseException thrown below
  409. }
  410. }
  411. throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  412. }
  413. } while ($this->moveToNextLine());
  414. if (null !== $tag) {
  415. $data = new TaggedValue($tag, $data);
  416. }
  417. if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && 'mapping' === $context && !\is_object($data)) {
  418. $object = new \stdClass();
  419. foreach ($data as $key => $value) {
  420. $object->$key = $value;
  421. }
  422. $data = $object;
  423. }
  424. return $data ?: null;
  425. }
  426. private function parseBlock(int $offset, string $yaml, int $flags): mixed
  427. {
  428. $skippedLineNumbers = $this->skippedLineNumbers;
  429. foreach ($this->locallySkippedLineNumbers as $lineNumber) {
  430. if ($lineNumber < $offset) {
  431. continue;
  432. }
  433. $skippedLineNumbers[] = $lineNumber;
  434. }
  435. $parser = new self();
  436. $parser->offset = $offset;
  437. $parser->totalNumberOfLines = $this->totalNumberOfLines;
  438. $parser->skippedLineNumbers = $skippedLineNumbers;
  439. $parser->refs = &$this->refs;
  440. $parser->refsBeingParsed = $this->refsBeingParsed;
  441. return $parser->doParse($yaml, $flags);
  442. }
  443. /**
  444. * Returns the current line number (takes the offset into account).
  445. *
  446. * @internal
  447. */
  448. public function getRealCurrentLineNb(): int
  449. {
  450. $realCurrentLineNumber = $this->currentLineNb + $this->offset;
  451. foreach ($this->skippedLineNumbers as $skippedLineNumber) {
  452. if ($skippedLineNumber > $realCurrentLineNumber) {
  453. break;
  454. }
  455. ++$realCurrentLineNumber;
  456. }
  457. return $realCurrentLineNumber;
  458. }
  459. private function getCurrentLineIndentation(): int
  460. {
  461. if (' ' !== ($this->currentLine[0] ?? '')) {
  462. return 0;
  463. }
  464. return \strlen($this->currentLine) - \strlen(ltrim($this->currentLine, ' '));
  465. }
  466. /**
  467. * Returns the next embed block of YAML.
  468. *
  469. * @param int|null $indentation The indent level at which the block is to be read, or null for default
  470. * @param bool $inSequence True if the enclosing data structure is a sequence
  471. *
  472. * @throws ParseException When indentation problem are detected
  473. */
  474. private function getNextEmbedBlock(?int $indentation = null, bool $inSequence = false): string
  475. {
  476. $oldLineIndentation = $this->getCurrentLineIndentation();
  477. if (!$this->moveToNextLine()) {
  478. return '';
  479. }
  480. if (null === $indentation) {
  481. $newIndent = null;
  482. $movements = 0;
  483. do {
  484. $EOF = false;
  485. // empty and comment-like lines do not influence the indentation depth
  486. if ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) {
  487. $EOF = !$this->moveToNextLine();
  488. if (!$EOF) {
  489. ++$movements;
  490. }
  491. } else {
  492. $newIndent = $this->getCurrentLineIndentation();
  493. }
  494. } while (!$EOF && null === $newIndent);
  495. for ($i = 0; $i < $movements; ++$i) {
  496. $this->moveToPreviousLine();
  497. }
  498. $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem();
  499. if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
  500. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  501. }
  502. } else {
  503. $newIndent = $indentation;
  504. }
  505. $data = [];
  506. if ($this->getCurrentLineIndentation() >= $newIndent) {
  507. $data[] = substr($this->currentLine, $newIndent ?? 0);
  508. } elseif ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) {
  509. $data[] = $this->currentLine;
  510. } else {
  511. $this->moveToPreviousLine();
  512. return '';
  513. }
  514. if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) {
  515. // the previous line contained a dash but no item content, this line is a sequence item with the same indentation
  516. // and therefore no nested list or mapping
  517. $this->moveToPreviousLine();
  518. return '';
  519. }
  520. $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
  521. $isItComment = $this->isCurrentLineComment();
  522. while ($this->moveToNextLine()) {
  523. if ($isItComment && !$isItUnindentedCollection) {
  524. $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
  525. $isItComment = $this->isCurrentLineComment();
  526. }
  527. $indent = $this->getCurrentLineIndentation();
  528. if ($isItUnindentedCollection && !$this->isCurrentLineEmpty() && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) {
  529. $this->moveToPreviousLine();
  530. break;
  531. }
  532. if ($this->isCurrentLineBlank()) {
  533. $data[] = substr($this->currentLine, $newIndent ?? 0);
  534. continue;
  535. }
  536. if ($indent >= $newIndent) {
  537. $data[] = substr($this->currentLine, $newIndent ?? 0);
  538. } elseif ($this->isCurrentLineComment()) {
  539. $data[] = $this->currentLine;
  540. } elseif (0 == $indent) {
  541. $this->moveToPreviousLine();
  542. break;
  543. } else {
  544. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  545. }
  546. }
  547. return implode("\n", $data);
  548. }
  549. private function hasMoreLines(): bool
  550. {
  551. return (\count($this->lines) - 1) > $this->currentLineNb;
  552. }
  553. /**
  554. * Moves the parser to the next line.
  555. */
  556. private function moveToNextLine(): bool
  557. {
  558. if ($this->currentLineNb >= $this->numberOfParsedLines - 1) {
  559. return false;
  560. }
  561. $this->currentLine = $this->lines[++$this->currentLineNb];
  562. return true;
  563. }
  564. /**
  565. * Moves the parser to the previous line.
  566. */
  567. private function moveToPreviousLine(): bool
  568. {
  569. if ($this->currentLineNb < 1) {
  570. return false;
  571. }
  572. $this->currentLine = $this->lines[--$this->currentLineNb];
  573. return true;
  574. }
  575. /**
  576. * Parses a YAML value.
  577. *
  578. * @param string $value A YAML value
  579. * @param int $flags A bit field of Yaml::PARSE_* constants to customize the YAML parser behavior
  580. * @param string $context The parser context (either sequence or mapping)
  581. *
  582. * @throws ParseException When reference does not exist
  583. */
  584. private function parseValue(string $value, int $flags, string $context): mixed
  585. {
  586. if (str_starts_with($value, '*')) {
  587. if (false !== $pos = strpos($value, '#')) {
  588. $value = substr($value, 1, $pos - 2);
  589. } else {
  590. $value = substr($value, 1);
  591. }
  592. if (!\array_key_exists($value, $this->refs)) {
  593. if (false !== $pos = array_search($value, $this->refsBeingParsed, true)) {
  594. 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);
  595. }
  596. throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine, $this->filename);
  597. }
  598. return $this->refs[$value];
  599. }
  600. if (\in_array($value[0], ['!', '|', '>'], true) && self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
  601. $modifiers = $matches['modifiers'] ?? '';
  602. $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), abs((int) $modifiers));
  603. if ('' !== $matches['tag'] && '!' !== $matches['tag']) {
  604. if ('!!binary' === $matches['tag']) {
  605. return Inline::evaluateBinaryScalar($data);
  606. }
  607. return new TaggedValue(substr($matches['tag'], 1), $data);
  608. }
  609. return $data;
  610. }
  611. try {
  612. if ('' !== $value && '{' === $value[0]) {
  613. $cursor = \strlen(rtrim($this->currentLine)) - \strlen(rtrim($value));
  614. return Inline::parse($this->lexInlineMapping($cursor), $flags, $this->refs);
  615. } elseif ('' !== $value && '[' === $value[0]) {
  616. $cursor = \strlen(rtrim($this->currentLine)) - \strlen(rtrim($value));
  617. return Inline::parse($this->lexInlineSequence($cursor), $flags, $this->refs);
  618. }
  619. switch ($value[0] ?? '') {
  620. case '"':
  621. case "'":
  622. $cursor = \strlen(rtrim($this->currentLine)) - \strlen(rtrim($value));
  623. $parsedValue = Inline::parse($this->lexInlineQuotedString($cursor), $flags, $this->refs);
  624. if (isset($this->currentLine[$cursor]) && preg_replace('/\s*(#.*)?$/A', '', substr($this->currentLine, $cursor))) {
  625. throw new ParseException(sprintf('Unexpected characters near "%s".', substr($this->currentLine, $cursor)));
  626. }
  627. return $parsedValue;
  628. default:
  629. $lines = [];
  630. while ($this->moveToNextLine()) {
  631. // unquoted strings end before the first unindented line
  632. if (0 === $this->getCurrentLineIndentation()) {
  633. $this->moveToPreviousLine();
  634. break;
  635. }
  636. $lines[] = trim($this->currentLine);
  637. }
  638. for ($i = 0, $linesCount = \count($lines), $previousLineBlank = false; $i < $linesCount; ++$i) {
  639. if ('' === $lines[$i]) {
  640. $value .= "\n";
  641. $previousLineBlank = true;
  642. } elseif ($previousLineBlank) {
  643. $value .= $lines[$i];
  644. $previousLineBlank = false;
  645. } else {
  646. $value .= ' '.$lines[$i];
  647. $previousLineBlank = false;
  648. }
  649. }
  650. Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
  651. $parsedValue = Inline::parse($value, $flags, $this->refs);
  652. if ('mapping' === $context && \is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && str_contains($parsedValue, ': ')) {
  653. throw new ParseException('A colon cannot be used in an unquoted mapping value.', $this->getRealCurrentLineNb() + 1, $value, $this->filename);
  654. }
  655. return $parsedValue;
  656. }
  657. } catch (ParseException $e) {
  658. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  659. $e->setSnippet($this->currentLine);
  660. throw $e;
  661. }
  662. }
  663. /**
  664. * Parses a block scalar.
  665. *
  666. * @param string $style The style indicator that was used to begin this block scalar (| or >)
  667. * @param string $chomping The chomping indicator that was used to begin this block scalar (+ or -)
  668. * @param int $indentation The indentation indicator that was used to begin this block scalar
  669. */
  670. private function parseBlockScalar(string $style, string $chomping = '', int $indentation = 0): string
  671. {
  672. $notEOF = $this->moveToNextLine();
  673. if (!$notEOF) {
  674. return '';
  675. }
  676. $isCurrentLineBlank = $this->isCurrentLineBlank();
  677. $blockLines = [];
  678. // leading blank lines are consumed before determining indentation
  679. while ($notEOF && $isCurrentLineBlank) {
  680. // newline only if not EOF
  681. if ($notEOF = $this->moveToNextLine()) {
  682. $blockLines[] = '';
  683. $isCurrentLineBlank = $this->isCurrentLineBlank();
  684. }
  685. }
  686. // determine indentation if not specified
  687. if (0 === $indentation) {
  688. $currentLineLength = \strlen($this->currentLine);
  689. for ($i = 0; $i < $currentLineLength && ' ' === $this->currentLine[$i]; ++$i) {
  690. ++$indentation;
  691. }
  692. }
  693. if ($indentation > 0) {
  694. $pattern = sprintf('/^ {%d}(.*)$/', $indentation);
  695. while (
  696. $notEOF && (
  697. $isCurrentLineBlank
  698. || self::preg_match($pattern, $this->currentLine, $matches)
  699. )
  700. ) {
  701. if ($isCurrentLineBlank && \strlen($this->currentLine) > $indentation) {
  702. $blockLines[] = substr($this->currentLine, $indentation);
  703. } elseif ($isCurrentLineBlank) {
  704. $blockLines[] = '';
  705. } else {
  706. $blockLines[] = $matches[1];
  707. }
  708. // newline only if not EOF
  709. if ($notEOF = $this->moveToNextLine()) {
  710. $isCurrentLineBlank = $this->isCurrentLineBlank();
  711. }
  712. }
  713. } elseif ($notEOF) {
  714. $blockLines[] = '';
  715. }
  716. if ($notEOF) {
  717. $blockLines[] = '';
  718. $this->moveToPreviousLine();
  719. } elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) {
  720. $blockLines[] = '';
  721. }
  722. // folded style
  723. if ('>' === $style) {
  724. $text = '';
  725. $previousLineIndented = false;
  726. $previousLineBlank = false;
  727. for ($i = 0, $blockLinesCount = \count($blockLines); $i < $blockLinesCount; ++$i) {
  728. if ('' === $blockLines[$i]) {
  729. $text .= "\n";
  730. $previousLineIndented = false;
  731. $previousLineBlank = true;
  732. } elseif (' ' === $blockLines[$i][0]) {
  733. $text .= "\n".$blockLines[$i];
  734. $previousLineIndented = true;
  735. $previousLineBlank = false;
  736. } elseif ($previousLineIndented) {
  737. $text .= "\n".$blockLines[$i];
  738. $previousLineIndented = false;
  739. $previousLineBlank = false;
  740. } elseif ($previousLineBlank || 0 === $i) {
  741. $text .= $blockLines[$i];
  742. $previousLineIndented = false;
  743. $previousLineBlank = false;
  744. } else {
  745. $text .= ' '.$blockLines[$i];
  746. $previousLineIndented = false;
  747. $previousLineBlank = false;
  748. }
  749. }
  750. } else {
  751. $text = implode("\n", $blockLines);
  752. }
  753. // deal with trailing newlines
  754. if ('' === $chomping) {
  755. $text = preg_replace('/\n+$/', "\n", $text);
  756. } elseif ('-' === $chomping) {
  757. $text = preg_replace('/\n+$/', '', $text);
  758. }
  759. return $text;
  760. }
  761. /**
  762. * Returns true if the next line is indented.
  763. */
  764. private function isNextLineIndented(): bool
  765. {
  766. $currentIndentation = $this->getCurrentLineIndentation();
  767. $movements = 0;
  768. do {
  769. $EOF = !$this->moveToNextLine();
  770. if (!$EOF) {
  771. ++$movements;
  772. }
  773. } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
  774. if ($EOF) {
  775. for ($i = 0; $i < $movements; ++$i) {
  776. $this->moveToPreviousLine();
  777. }
  778. return false;
  779. }
  780. $ret = $this->getCurrentLineIndentation() > $currentIndentation;
  781. for ($i = 0; $i < $movements; ++$i) {
  782. $this->moveToPreviousLine();
  783. }
  784. return $ret;
  785. }
  786. private function isCurrentLineEmpty(): bool
  787. {
  788. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  789. }
  790. private function isCurrentLineBlank(): bool
  791. {
  792. return '' === $this->currentLine || '' === trim($this->currentLine, ' ');
  793. }
  794. private function isCurrentLineComment(): bool
  795. {
  796. // checking explicitly the first char of the trim is faster than loops or strpos
  797. $ltrimmedLine = '' !== $this->currentLine && ' ' === $this->currentLine[0] ? ltrim($this->currentLine, ' ') : $this->currentLine;
  798. return '' !== $ltrimmedLine && '#' === $ltrimmedLine[0];
  799. }
  800. private function isCurrentLineLastLineInDocument(): bool
  801. {
  802. return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1);
  803. }
  804. private function cleanup(string $value): string
  805. {
  806. $value = str_replace(["\r\n", "\r"], "\n", $value);
  807. // strip YAML header
  808. $count = 0;
  809. $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
  810. $this->offset += $count;
  811. // remove leading comments
  812. $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
  813. if (1 === $count) {
  814. // items have been removed, update the offset
  815. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  816. $value = $trimmedValue;
  817. }
  818. // remove start of the document marker (---)
  819. $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
  820. if (1 === $count) {
  821. // items have been removed, update the offset
  822. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  823. $value = $trimmedValue;
  824. // remove end of the document marker (...)
  825. $value = preg_replace('#\.\.\.\s*$#', '', $value);
  826. }
  827. return $value;
  828. }
  829. private function isNextLineUnIndentedCollection(): bool
  830. {
  831. $currentIndentation = $this->getCurrentLineIndentation();
  832. $movements = 0;
  833. do {
  834. $EOF = !$this->moveToNextLine();
  835. if (!$EOF) {
  836. ++$movements;
  837. }
  838. } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
  839. if ($EOF) {
  840. return false;
  841. }
  842. $ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem();
  843. for ($i = 0; $i < $movements; ++$i) {
  844. $this->moveToPreviousLine();
  845. }
  846. return $ret;
  847. }
  848. private function isStringUnIndentedCollectionItem(): bool
  849. {
  850. return '-' === rtrim($this->currentLine) || str_starts_with($this->currentLine, '- ');
  851. }
  852. /**
  853. * A local wrapper for "preg_match" which will throw a ParseException if there
  854. * is an internal error in the PCRE engine.
  855. *
  856. * This avoids us needing to check for "false" every time PCRE is used
  857. * in the YAML engine
  858. *
  859. * @throws ParseException on a PCRE internal error
  860. *
  861. * @internal
  862. */
  863. public static function preg_match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int
  864. {
  865. if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) {
  866. throw new ParseException(preg_last_error_msg());
  867. }
  868. return $ret;
  869. }
  870. /**
  871. * Trim the tag on top of the value.
  872. *
  873. * Prevent values such as "!foo {quz: bar}" to be considered as
  874. * a mapping block.
  875. */
  876. private function trimTag(string $value): string
  877. {
  878. if ('!' === $value[0]) {
  879. return ltrim(substr($value, 1, strcspn($value, " \r\n", 1)), ' ');
  880. }
  881. return $value;
  882. }
  883. private function getLineTag(string $value, int $flags, bool $nextLineCheck = true): ?string
  884. {
  885. if ('' === $value || '!' !== $value[0] || 1 !== self::preg_match('/^'.self::TAG_PATTERN.' *( +#.*)?$/', $value, $matches)) {
  886. return null;
  887. }
  888. if ($nextLineCheck && !$this->isNextLineIndented()) {
  889. return null;
  890. }
  891. $tag = substr($matches['tag'], 1);
  892. // Built-in tags
  893. if ($tag && '!' === $tag[0]) {
  894. throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag), $this->getRealCurrentLineNb() + 1, $value, $this->filename);
  895. }
  896. if (Yaml::PARSE_CUSTOM_TAGS & $flags) {
  897. return $tag;
  898. }
  899. 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);
  900. }
  901. private function lexInlineQuotedString(int &$cursor = 0): string
  902. {
  903. $quotation = $this->currentLine[$cursor];
  904. $value = $quotation;
  905. ++$cursor;
  906. $previousLineWasNewline = true;
  907. $previousLineWasTerminatedWithBackslash = false;
  908. $lineNumber = 0;
  909. do {
  910. if (++$lineNumber > 1) {
  911. $cursor += strspn($this->currentLine, ' ', $cursor);
  912. }
  913. if ($this->isCurrentLineBlank()) {
  914. $value .= "\n";
  915. } elseif (!$previousLineWasNewline && !$previousLineWasTerminatedWithBackslash) {
  916. $value .= ' ';
  917. }
  918. for (; \strlen($this->currentLine) > $cursor; ++$cursor) {
  919. switch ($this->currentLine[$cursor]) {
  920. case '\\':
  921. if ("'" === $quotation) {
  922. $value .= '\\';
  923. } elseif (isset($this->currentLine[++$cursor])) {
  924. $value .= '\\'.$this->currentLine[$cursor];
  925. }
  926. break;
  927. case $quotation:
  928. ++$cursor;
  929. if ("'" === $quotation && isset($this->currentLine[$cursor]) && "'" === $this->currentLine[$cursor]) {
  930. $value .= "''";
  931. break;
  932. }
  933. return $value.$quotation;
  934. default:
  935. $value .= $this->currentLine[$cursor];
  936. }
  937. }
  938. if ($this->isCurrentLineBlank()) {
  939. $previousLineWasNewline = true;
  940. $previousLineWasTerminatedWithBackslash = false;
  941. } elseif ('\\' === $this->currentLine[-1]) {
  942. $previousLineWasNewline = false;
  943. $previousLineWasTerminatedWithBackslash = true;
  944. } else {
  945. $previousLineWasNewline = false;
  946. $previousLineWasTerminatedWithBackslash = false;
  947. }
  948. if ($this->hasMoreLines()) {
  949. $cursor = 0;
  950. }
  951. } while ($this->moveToNextLine());
  952. throw new ParseException('Malformed inline YAML string.');
  953. }
  954. private function lexUnquotedString(int &$cursor): string
  955. {
  956. $offset = $cursor;
  957. $cursor += strcspn($this->currentLine, '[]{},: ', $cursor);
  958. if ($cursor === $offset) {
  959. throw new ParseException('Malformed unquoted YAML string.');
  960. }
  961. return substr($this->currentLine, $offset, $cursor - $offset);
  962. }
  963. private function lexInlineMapping(int &$cursor = 0): string
  964. {
  965. return $this->lexInlineStructure($cursor, '}');
  966. }
  967. private function lexInlineSequence(int &$cursor = 0): string
  968. {
  969. return $this->lexInlineStructure($cursor, ']');
  970. }
  971. private function lexInlineStructure(int &$cursor, string $closingTag): string
  972. {
  973. $value = $this->currentLine[$cursor];
  974. ++$cursor;
  975. do {
  976. $this->consumeWhitespaces($cursor);
  977. while (isset($this->currentLine[$cursor])) {
  978. switch ($this->currentLine[$cursor]) {
  979. case '"':
  980. case "'":
  981. $value .= $this->lexInlineQuotedString($cursor);
  982. break;
  983. case ':':
  984. case ',':
  985. $value .= $this->currentLine[$cursor];
  986. ++$cursor;
  987. break;
  988. case '{':
  989. $value .= $this->lexInlineMapping($cursor);
  990. break;
  991. case '[':
  992. $value .= $this->lexInlineSequence($cursor);
  993. break;
  994. case $closingTag:
  995. $value .= $this->currentLine[$cursor];
  996. ++$cursor;
  997. return $value;
  998. case '#':
  999. break 2;
  1000. default:
  1001. $value .= $this->lexUnquotedString($cursor);
  1002. }
  1003. if ($this->consumeWhitespaces($cursor)) {
  1004. $value .= ' ';
  1005. }
  1006. }
  1007. if ($this->hasMoreLines()) {
  1008. $cursor = 0;
  1009. }
  1010. } while ($this->moveToNextLine());
  1011. throw new ParseException('Malformed inline YAML string.');
  1012. }
  1013. private function consumeWhitespaces(int &$cursor): bool
  1014. {
  1015. $whitespacesConsumed = 0;
  1016. do {
  1017. $whitespaceOnlyTokenLength = strspn($this->currentLine, ' ', $cursor);
  1018. $whitespacesConsumed += $whitespaceOnlyTokenLength;
  1019. $cursor += $whitespaceOnlyTokenLength;
  1020. if (isset($this->currentLine[$cursor])) {
  1021. return 0 < $whitespacesConsumed;
  1022. }
  1023. if ($this->hasMoreLines()) {
  1024. $cursor = 0;
  1025. }
  1026. } while ($this->moveToNextLine());
  1027. return 0 < $whitespacesConsumed;
  1028. }
  1029. }