| Total Complexity | 222 |
| Total Lines | 802 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like Inline often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Inline, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 25 | class Inline |
||
| 26 | { |
||
| 27 | public const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*+(?:\\\\.[^"\\\\]*+)*+)"|\'([^\']*+(?:\'\'[^\']*+)*+)\')'; |
||
| 28 | |||
| 29 | public static $parsedLineNumber = -1; |
||
| 30 | public static $parsedFilename; |
||
| 31 | |||
| 32 | private static $exceptionOnInvalidType = false; |
||
| 33 | private static $objectSupport = false; |
||
| 34 | private static $objectForMap = false; |
||
| 35 | private static $constantSupport = false; |
||
| 36 | |||
| 37 | public static function initialize(int $flags, ?int $parsedLineNumber = null, ?string $parsedFilename = null) |
||
| 38 | { |
||
| 39 | self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags); |
||
| 40 | self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags); |
||
| 41 | self::$objectForMap = (bool) (Yaml::PARSE_OBJECT_FOR_MAP & $flags); |
||
| 42 | self::$constantSupport = (bool) (Yaml::PARSE_CONSTANT & $flags); |
||
| 43 | self::$parsedFilename = $parsedFilename; |
||
| 44 | |||
| 45 | if (null !== $parsedLineNumber) { |
||
| 46 | self::$parsedLineNumber = $parsedLineNumber; |
||
| 47 | } |
||
| 48 | } |
||
| 49 | |||
| 50 | /** |
||
| 51 | * Converts a YAML string to a PHP value. |
||
| 52 | * |
||
| 53 | * @param string|null $value A YAML string |
||
| 54 | * @param int $flags A bit field of Yaml::PARSE_* constants to customize the YAML parser behavior |
||
| 55 | * @param array $references Mapping of variable names to values |
||
| 56 | * |
||
| 57 | * @return mixed |
||
| 58 | * |
||
| 59 | * @throws ParseException |
||
| 60 | */ |
||
| 61 | public static function parse(?string $value = null, int $flags = 0, array &$references = []) |
||
| 62 | { |
||
| 63 | if (null === $value) { |
||
| 64 | return ''; |
||
| 65 | } |
||
| 66 | |||
| 67 | self::initialize($flags); |
||
| 68 | |||
| 69 | $value = trim($value); |
||
| 70 | |||
| 71 | if ('' === $value) { |
||
| 72 | return ''; |
||
| 73 | } |
||
| 74 | |||
| 75 | if (2 /* MB_OVERLOAD_STRING */ & (int) \ini_get('mbstring.func_overload')) { |
||
| 76 | $mbEncoding = mb_internal_encoding(); |
||
| 77 | mb_internal_encoding('ASCII'); |
||
| 78 | } |
||
| 79 | |||
| 80 | try { |
||
| 81 | $i = 0; |
||
| 82 | $tag = self::parseTag($value, $i, $flags); |
||
| 83 | switch ($value[$i]) { |
||
| 84 | case '[': |
||
| 85 | $result = self::parseSequence($value, $flags, $i, $references); |
||
| 86 | ++$i; |
||
| 87 | break; |
||
| 88 | case '{': |
||
| 89 | $result = self::parseMapping($value, $flags, $i, $references); |
||
| 90 | ++$i; |
||
| 91 | break; |
||
| 92 | default: |
||
| 93 | $result = self::parseScalar($value, $flags, null, $i, true, $references); |
||
| 94 | } |
||
| 95 | |||
| 96 | // some comments are allowed at the end |
||
| 97 | if (preg_replace('/\s*#.*$/A', '', substr($value, $i))) { |
||
| 98 | throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)), self::$parsedLineNumber + 1, $value, self::$parsedFilename); |
||
| 99 | } |
||
| 100 | |||
| 101 | if (null !== $tag && '' !== $tag) { |
||
| 102 | return new TaggedValue($tag, $result); |
||
| 103 | } |
||
| 104 | |||
| 105 | return $result; |
||
| 106 | } finally { |
||
| 107 | if (isset($mbEncoding)) { |
||
| 108 | mb_internal_encoding($mbEncoding); |
||
| 109 | } |
||
| 110 | } |
||
| 111 | } |
||
| 112 | |||
| 113 | /** |
||
| 114 | * Dumps a given PHP variable to a YAML string. |
||
| 115 | * |
||
| 116 | * @param mixed $value The PHP variable to convert |
||
| 117 | * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string |
||
| 118 | * |
||
| 119 | * @throws DumpException When trying to dump PHP resource |
||
| 120 | */ |
||
| 121 | public static function dump($value, int $flags = 0): string |
||
| 122 | { |
||
| 123 | switch (true) { |
||
| 124 | case \is_resource($value): |
||
| 125 | if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) { |
||
| 126 | throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value))); |
||
| 127 | } |
||
| 128 | |||
| 129 | return self::dumpNull($flags); |
||
| 130 | case $value instanceof \DateTimeInterface: |
||
| 131 | return $value->format('c'); |
||
| 132 | case $value instanceof \UnitEnum: |
||
| 133 | return sprintf('!php/const %s::%s', \get_class($value), $value->name); |
||
| 134 | case \is_object($value): |
||
| 135 | if ($value instanceof TaggedValue) { |
||
| 136 | return '!'.$value->getTag().' '.self::dump($value->getValue(), $flags); |
||
| 137 | } |
||
| 138 | |||
| 139 | if (Yaml::DUMP_OBJECT & $flags) { |
||
| 140 | return '!php/object '.self::dump(serialize($value)); |
||
| 141 | } |
||
| 142 | |||
| 143 | if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) { |
||
| 144 | $output = []; |
||
| 145 | |||
| 146 | foreach ($value as $key => $val) { |
||
| 147 | $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags)); |
||
| 148 | } |
||
| 149 | |||
| 150 | return sprintf('{ %s }', implode(', ', $output)); |
||
| 151 | } |
||
| 152 | |||
| 153 | if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) { |
||
| 154 | throw new DumpException('Object support when dumping a YAML file has been disabled.'); |
||
| 155 | } |
||
| 156 | |||
| 157 | return self::dumpNull($flags); |
||
| 158 | case \is_array($value): |
||
| 159 | return self::dumpArray($value, $flags); |
||
| 160 | case null === $value: |
||
| 161 | return self::dumpNull($flags); |
||
| 162 | case true === $value: |
||
| 163 | return 'true'; |
||
| 164 | case false === $value: |
||
| 165 | return 'false'; |
||
| 166 | case \is_int($value): |
||
| 167 | return $value; |
||
| 168 | case is_numeric($value) && false === strpbrk($value, "\f\n\r\t\v"): |
||
| 169 | $locale = setlocale(\LC_NUMERIC, 0); |
||
| 170 | if (false !== $locale) { |
||
| 171 | setlocale(\LC_NUMERIC, 'C'); |
||
| 172 | } |
||
| 173 | if (\is_float($value)) { |
||
| 174 | $repr = (string) $value; |
||
| 175 | if (is_infinite($value)) { |
||
| 176 | $repr = str_ireplace('INF', '.Inf', $repr); |
||
| 177 | } elseif (floor($value) == $value && $repr == $value) { |
||
| 178 | // Preserve float data type since storing a whole number will result in integer value. |
||
| 179 | if (false === strpos($repr, 'E')) { |
||
| 180 | $repr = $repr.'.0'; |
||
| 181 | } |
||
| 182 | } |
||
| 183 | } else { |
||
| 184 | $repr = \is_string($value) ? "'$value'" : (string) $value; |
||
| 185 | } |
||
| 186 | if (false !== $locale) { |
||
| 187 | setlocale(\LC_NUMERIC, $locale); |
||
| 188 | } |
||
| 189 | |||
| 190 | return $repr; |
||
| 191 | case '' == $value: |
||
| 192 | return "''"; |
||
| 193 | case self::isBinaryString($value): |
||
| 194 | return '!!binary '.base64_encode($value); |
||
| 195 | case Escaper::requiresDoubleQuoting($value): |
||
| 196 | return Escaper::escapeWithDoubleQuotes($value); |
||
| 197 | case Escaper::requiresSingleQuoting($value): |
||
| 198 | case Parser::preg_match('{^[0-9]+[_0-9]*$}', $value): |
||
| 199 | case Parser::preg_match(self::getHexRegex(), $value): |
||
| 200 | case Parser::preg_match(self::getTimestampRegex(), $value): |
||
| 201 | return Escaper::escapeWithSingleQuotes($value); |
||
| 202 | default: |
||
| 203 | return $value; |
||
| 204 | } |
||
| 205 | } |
||
| 206 | |||
| 207 | /** |
||
| 208 | * Check if given array is hash or just normal indexed array. |
||
| 209 | * |
||
| 210 | * @param array|\ArrayObject|\stdClass $value The PHP array or array-like object to check |
||
| 211 | */ |
||
| 212 | public static function isHash($value): bool |
||
| 213 | { |
||
| 214 | if ($value instanceof \stdClass || $value instanceof \ArrayObject) { |
||
| 215 | return true; |
||
| 216 | } |
||
| 217 | |||
| 218 | $expectedKey = 0; |
||
| 219 | |||
| 220 | foreach ($value as $key => $val) { |
||
| 221 | if ($key !== $expectedKey++) { |
||
| 222 | return true; |
||
| 223 | } |
||
| 224 | } |
||
| 225 | |||
| 226 | return false; |
||
| 227 | } |
||
| 228 | |||
| 229 | /** |
||
| 230 | * Dumps a PHP array to a YAML string. |
||
| 231 | * |
||
| 232 | * @param array $value The PHP array to dump |
||
| 233 | * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string |
||
| 234 | */ |
||
| 235 | private static function dumpArray(array $value, int $flags): string |
||
| 236 | { |
||
| 237 | // array |
||
| 238 | if (($value || Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE & $flags) && !self::isHash($value)) { |
||
| 239 | $output = []; |
||
| 240 | foreach ($value as $val) { |
||
| 241 | $output[] = self::dump($val, $flags); |
||
| 242 | } |
||
| 243 | |||
| 244 | return sprintf('[%s]', implode(', ', $output)); |
||
| 245 | } |
||
| 246 | |||
| 247 | // hash |
||
| 248 | $output = []; |
||
| 249 | foreach ($value as $key => $val) { |
||
| 250 | $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags)); |
||
| 251 | } |
||
| 252 | |||
| 253 | return sprintf('{ %s }', implode(', ', $output)); |
||
| 254 | } |
||
| 255 | |||
| 256 | private static function dumpNull(int $flags): string |
||
| 257 | { |
||
| 258 | if (Yaml::DUMP_NULL_AS_TILDE & $flags) { |
||
| 259 | return '~'; |
||
| 260 | } |
||
| 261 | |||
| 262 | return 'null'; |
||
| 263 | } |
||
| 264 | |||
| 265 | /** |
||
| 266 | * Parses a YAML scalar. |
||
| 267 | * |
||
| 268 | * @return mixed |
||
| 269 | * |
||
| 270 | * @throws ParseException When malformed inline YAML string is parsed |
||
| 271 | */ |
||
| 272 | public static function parseScalar(string $scalar, int $flags = 0, ?array $delimiters = null, int &$i = 0, bool $evaluate = true, array &$references = [], ?bool &$isQuoted = null) |
||
| 273 | { |
||
| 274 | if (\in_array($scalar[$i], ['"', "'"], true)) { |
||
| 275 | // quoted scalar |
||
| 276 | $isQuoted = true; |
||
| 277 | $output = self::parseQuotedScalar($scalar, $i); |
||
| 278 | |||
| 279 | if (null !== $delimiters) { |
||
| 280 | $tmp = ltrim(substr($scalar, $i), " \n"); |
||
| 281 | if ('' === $tmp) { |
||
| 282 | throw new ParseException(sprintf('Unexpected end of line, expected one of "%s".', implode('', $delimiters)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); |
||
| 283 | } |
||
| 284 | if (!\in_array($tmp[0], $delimiters)) { |
||
| 285 | throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); |
||
| 286 | } |
||
| 287 | } |
||
| 288 | } else { |
||
| 289 | // "normal" string |
||
| 290 | $isQuoted = false; |
||
| 291 | |||
| 292 | if (!$delimiters) { |
||
| 293 | $output = substr($scalar, $i); |
||
| 294 | $i += \strlen($output); |
||
| 295 | |||
| 296 | // remove comments |
||
| 297 | if (Parser::preg_match('/[ \t]+#/', $output, $match, \PREG_OFFSET_CAPTURE)) { |
||
| 298 | $output = substr($output, 0, $match[0][1]); |
||
| 299 | } |
||
| 300 | } elseif (Parser::preg_match('/^(.*?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) { |
||
| 301 | $output = $match[1]; |
||
| 302 | $i += \strlen($output); |
||
| 303 | $output = trim($output); |
||
| 304 | } else { |
||
| 305 | throw new ParseException(sprintf('Malformed inline YAML string: "%s".', $scalar), self::$parsedLineNumber + 1, null, self::$parsedFilename); |
||
| 306 | } |
||
| 307 | |||
| 308 | // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >) |
||
| 309 | if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0] || '%' === $output[0])) { |
||
| 310 | throw new ParseException(sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0]), self::$parsedLineNumber + 1, $output, self::$parsedFilename); |
||
| 311 | } |
||
| 312 | |||
| 313 | if ($evaluate) { |
||
| 314 | $output = self::evaluateScalar($output, $flags, $references, $isQuoted); |
||
| 315 | } |
||
| 316 | } |
||
| 317 | |||
| 318 | return $output; |
||
| 319 | } |
||
| 320 | |||
| 321 | /** |
||
| 322 | * Parses a YAML quoted scalar. |
||
| 323 | * |
||
| 324 | * @throws ParseException When malformed inline YAML string is parsed |
||
| 325 | */ |
||
| 326 | private static function parseQuotedScalar(string $scalar, int &$i = 0): string |
||
| 327 | { |
||
| 328 | if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) { |
||
| 329 | throw new ParseException(sprintf('Malformed inline YAML string: "%s".', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); |
||
| 330 | } |
||
| 331 | |||
| 332 | $output = substr($match[0], 1, -1); |
||
| 333 | |||
| 334 | $unescaper = new Unescaper(); |
||
| 335 | if ('"' == $scalar[$i]) { |
||
| 336 | $output = $unescaper->unescapeDoubleQuotedString($output); |
||
| 337 | } else { |
||
| 338 | $output = $unescaper->unescapeSingleQuotedString($output); |
||
| 339 | } |
||
| 340 | |||
| 341 | $i += \strlen($match[0]); |
||
| 342 | |||
| 343 | return $output; |
||
| 344 | } |
||
| 345 | |||
| 346 | /** |
||
| 347 | * Parses a YAML sequence. |
||
| 348 | * |
||
| 349 | * @throws ParseException When malformed inline YAML string is parsed |
||
| 350 | */ |
||
| 351 | private static function parseSequence(string $sequence, int $flags, int &$i = 0, array &$references = []): array |
||
| 352 | { |
||
| 353 | $output = []; |
||
| 354 | $len = \strlen($sequence); |
||
| 355 | ++$i; |
||
| 356 | |||
| 357 | // [foo, bar, ...] |
||
| 358 | $lastToken = null; |
||
| 359 | while ($i < $len) { |
||
| 360 | if (']' === $sequence[$i]) { |
||
| 361 | return $output; |
||
| 362 | } |
||
| 363 | if (',' === $sequence[$i] || ' ' === $sequence[$i]) { |
||
| 364 | if (',' === $sequence[$i] && (null === $lastToken || 'separator' === $lastToken)) { |
||
| 365 | $output[] = null; |
||
| 366 | } elseif (',' === $sequence[$i]) { |
||
| 367 | $lastToken = 'separator'; |
||
| 368 | } |
||
| 369 | |||
| 370 | ++$i; |
||
| 371 | |||
| 372 | continue; |
||
| 373 | } |
||
| 374 | |||
| 375 | $tag = self::parseTag($sequence, $i, $flags); |
||
| 376 | switch ($sequence[$i]) { |
||
| 377 | case '[': |
||
| 378 | // nested sequence |
||
| 379 | $value = self::parseSequence($sequence, $flags, $i, $references); |
||
| 380 | break; |
||
| 381 | case '{': |
||
| 382 | // nested mapping |
||
| 383 | $value = self::parseMapping($sequence, $flags, $i, $references); |
||
| 384 | break; |
||
| 385 | default: |
||
| 386 | $value = self::parseScalar($sequence, $flags, [',', ']'], $i, null === $tag, $references, $isQuoted); |
||
| 387 | |||
| 388 | // the value can be an array if a reference has been resolved to an array var |
||
| 389 | if (\is_string($value) && !$isQuoted && false !== strpos($value, ': ')) { |
||
| 390 | // embedded mapping? |
||
| 391 | try { |
||
| 392 | $pos = 0; |
||
| 393 | $value = self::parseMapping('{'.$value.'}', $flags, $pos, $references); |
||
| 394 | } catch (\InvalidArgumentException $e) { |
||
| 395 | // no, it's not |
||
| 396 | } |
||
| 397 | } |
||
| 398 | |||
| 399 | if (!$isQuoted && \is_string($value) && '' !== $value && '&' === $value[0] && Parser::preg_match(Parser::REFERENCE_PATTERN, $value, $matches)) { |
||
| 400 | $references[$matches['ref']] = $matches['value']; |
||
| 401 | $value = $matches['value']; |
||
| 402 | } |
||
| 403 | |||
| 404 | --$i; |
||
| 405 | } |
||
| 406 | |||
| 407 | if (null !== $tag && '' !== $tag) { |
||
| 408 | $value = new TaggedValue($tag, $value); |
||
| 409 | } |
||
| 410 | |||
| 411 | $output[] = $value; |
||
| 412 | |||
| 413 | $lastToken = 'value'; |
||
| 414 | ++$i; |
||
| 415 | } |
||
| 416 | |||
| 417 | throw new ParseException(sprintf('Malformed inline YAML string: "%s".', $sequence), self::$parsedLineNumber + 1, null, self::$parsedFilename); |
||
| 418 | } |
||
| 419 | |||
| 420 | /** |
||
| 421 | * Parses a YAML mapping. |
||
| 422 | * |
||
| 423 | * @return array|\stdClass |
||
| 424 | * |
||
| 425 | * @throws ParseException When malformed inline YAML string is parsed |
||
| 426 | */ |
||
| 427 | private static function parseMapping(string $mapping, int $flags, int &$i = 0, array &$references = []) |
||
| 428 | { |
||
| 429 | $output = []; |
||
| 430 | $len = \strlen($mapping); |
||
| 431 | ++$i; |
||
| 432 | $allowOverwrite = false; |
||
| 433 | |||
| 434 | // {foo: bar, bar:foo, ...} |
||
| 435 | while ($i < $len) { |
||
| 436 | switch ($mapping[$i]) { |
||
| 437 | case ' ': |
||
| 438 | case ',': |
||
| 439 | case "\n": |
||
| 440 | ++$i; |
||
| 441 | continue 2; |
||
| 442 | case '}': |
||
| 443 | if (self::$objectForMap) { |
||
| 444 | return (object) $output; |
||
| 445 | } |
||
| 446 | |||
| 447 | return $output; |
||
| 448 | } |
||
| 449 | |||
| 450 | // key |
||
| 451 | $offsetBeforeKeyParsing = $i; |
||
| 452 | $isKeyQuoted = \in_array($mapping[$i], ['"', "'"], true); |
||
| 453 | $key = self::parseScalar($mapping, $flags, [':', ' '], $i, false); |
||
| 454 | |||
| 455 | if ($offsetBeforeKeyParsing === $i) { |
||
| 456 | throw new ParseException('Missing mapping key.', self::$parsedLineNumber + 1, $mapping); |
||
| 457 | } |
||
| 458 | |||
| 459 | if ('!php/const' === $key) { |
||
| 460 | $key .= ' '.self::parseScalar($mapping, $flags, [':'], $i, false); |
||
| 461 | $key = self::evaluateScalar($key, $flags); |
||
| 462 | } |
||
| 463 | |||
| 464 | if (false === $i = strpos($mapping, ':', $i)) { |
||
| 465 | break; |
||
| 466 | } |
||
| 467 | |||
| 468 | if (!$isKeyQuoted) { |
||
| 469 | $evaluatedKey = self::evaluateScalar($key, $flags, $references); |
||
| 470 | |||
| 471 | if ('' !== $key && $evaluatedKey !== $key && !\is_string($evaluatedKey) && !\is_int($evaluatedKey)) { |
||
| 472 | throw new ParseException('Implicit casting of incompatible mapping keys to strings is not supported. Quote your evaluable mapping keys instead.', self::$parsedLineNumber + 1, $mapping); |
||
| 473 | } |
||
| 474 | } |
||
| 475 | |||
| 476 | if (!$isKeyQuoted && (!isset($mapping[$i + 1]) || !\in_array($mapping[$i + 1], [' ', ',', '[', ']', '{', '}', "\n"], true))) { |
||
| 477 | throw new ParseException('Colons must be followed by a space or an indication character (i.e. " ", ",", "[", "]", "{", "}").', self::$parsedLineNumber + 1, $mapping); |
||
| 478 | } |
||
| 479 | |||
| 480 | if ('<<' === $key) { |
||
| 481 | $allowOverwrite = true; |
||
| 482 | } |
||
| 483 | |||
| 484 | while ($i < $len) { |
||
| 485 | if (':' === $mapping[$i] || ' ' === $mapping[$i] || "\n" === $mapping[$i]) { |
||
| 486 | ++$i; |
||
| 487 | |||
| 488 | continue; |
||
| 489 | } |
||
| 490 | |||
| 491 | $tag = self::parseTag($mapping, $i, $flags); |
||
| 492 | switch ($mapping[$i]) { |
||
| 493 | case '[': |
||
| 494 | // nested sequence |
||
| 495 | $value = self::parseSequence($mapping, $flags, $i, $references); |
||
| 496 | // Spec: Keys MUST be unique; first one wins. |
||
| 497 | // Parser cannot abort this mapping earlier, since lines |
||
| 498 | // are processed sequentially. |
||
| 499 | // But overwriting is allowed when a merge node is used in current block. |
||
| 500 | if ('<<' === $key) { |
||
| 501 | foreach ($value as $parsedValue) { |
||
| 502 | $output += $parsedValue; |
||
| 503 | } |
||
| 504 | } elseif ($allowOverwrite || !isset($output[$key])) { |
||
| 505 | if (null !== $tag) { |
||
| 506 | $output[$key] = new TaggedValue($tag, $value); |
||
| 507 | } else { |
||
| 508 | $output[$key] = $value; |
||
| 509 | } |
||
| 510 | } elseif (isset($output[$key])) { |
||
| 511 | throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping); |
||
| 512 | } |
||
| 513 | break; |
||
| 514 | case '{': |
||
| 515 | // nested mapping |
||
| 516 | $value = self::parseMapping($mapping, $flags, $i, $references); |
||
| 517 | // Spec: Keys MUST be unique; first one wins. |
||
| 518 | // Parser cannot abort this mapping earlier, since lines |
||
| 519 | // are processed sequentially. |
||
| 520 | // But overwriting is allowed when a merge node is used in current block. |
||
| 521 | if ('<<' === $key) { |
||
| 522 | $output += $value; |
||
| 523 | } elseif ($allowOverwrite || !isset($output[$key])) { |
||
| 524 | if (null !== $tag) { |
||
| 525 | $output[$key] = new TaggedValue($tag, $value); |
||
| 526 | } else { |
||
| 527 | $output[$key] = $value; |
||
| 528 | } |
||
| 529 | } elseif (isset($output[$key])) { |
||
| 530 | throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping); |
||
| 531 | } |
||
| 532 | break; |
||
| 533 | default: |
||
| 534 | $value = self::parseScalar($mapping, $flags, [',', '}', "\n"], $i, null === $tag, $references, $isValueQuoted); |
||
| 535 | // Spec: Keys MUST be unique; first one wins. |
||
| 536 | // Parser cannot abort this mapping earlier, since lines |
||
| 537 | // are processed sequentially. |
||
| 538 | // But overwriting is allowed when a merge node is used in current block. |
||
| 539 | if ('<<' === $key) { |
||
| 540 | $output += $value; |
||
| 541 | } elseif ($allowOverwrite || !isset($output[$key])) { |
||
| 542 | if (!$isValueQuoted && \is_string($value) && '' !== $value && '&' === $value[0] && !self::isBinaryString($value) && Parser::preg_match(Parser::REFERENCE_PATTERN, $value, $matches)) { |
||
| 543 | $references[$matches['ref']] = $matches['value']; |
||
| 544 | $value = $matches['value']; |
||
| 545 | } |
||
| 546 | |||
| 547 | if (null !== $tag) { |
||
| 548 | $output[$key] = new TaggedValue($tag, $value); |
||
| 549 | } else { |
||
| 550 | $output[$key] = $value; |
||
| 551 | } |
||
| 552 | } elseif (isset($output[$key])) { |
||
| 553 | throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping); |
||
| 554 | } |
||
| 555 | --$i; |
||
| 556 | } |
||
| 557 | ++$i; |
||
| 558 | |||
| 559 | continue 2; |
||
| 560 | } |
||
| 561 | } |
||
| 562 | |||
| 563 | throw new ParseException(sprintf('Malformed inline YAML string: "%s".', $mapping), self::$parsedLineNumber + 1, null, self::$parsedFilename); |
||
| 564 | } |
||
| 565 | |||
| 566 | /** |
||
| 567 | * Evaluates scalars and replaces magic values. |
||
| 568 | * |
||
| 569 | * @return mixed |
||
| 570 | * |
||
| 571 | * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved |
||
| 572 | */ |
||
| 573 | private static function evaluateScalar(string $scalar, int $flags, array &$references = [], ?bool &$isQuotedString = null) |
||
| 574 | { |
||
| 575 | $isQuotedString = false; |
||
| 576 | $scalar = trim($scalar); |
||
| 577 | |||
| 578 | if (0 === strpos($scalar, '*')) { |
||
| 579 | if (false !== $pos = strpos($scalar, '#')) { |
||
| 580 | $value = substr($scalar, 1, $pos - 2); |
||
| 581 | } else { |
||
| 582 | $value = substr($scalar, 1); |
||
| 583 | } |
||
| 584 | |||
| 585 | // an unquoted * |
||
| 586 | if (false === $value || '' === $value) { |
||
| 587 | throw new ParseException('A reference must contain at least one character.', self::$parsedLineNumber + 1, $value, self::$parsedFilename); |
||
| 588 | } |
||
| 589 | |||
| 590 | if (!\array_key_exists($value, $references)) { |
||
| 591 | throw new ParseException(sprintf('Reference "%s" does not exist.', $value), self::$parsedLineNumber + 1, $value, self::$parsedFilename); |
||
| 592 | } |
||
| 593 | |||
| 594 | return $references[$value]; |
||
| 595 | } |
||
| 596 | |||
| 597 | $scalarLower = strtolower($scalar); |
||
| 598 | |||
| 599 | switch (true) { |
||
| 600 | case 'null' === $scalarLower: |
||
| 601 | case '' === $scalar: |
||
| 602 | case '~' === $scalar: |
||
| 603 | return null; |
||
| 604 | case 'true' === $scalarLower: |
||
| 605 | return true; |
||
| 606 | case 'false' === $scalarLower: |
||
| 607 | return false; |
||
| 608 | case '!' === $scalar[0]: |
||
| 609 | switch (true) { |
||
| 610 | case 0 === strpos($scalar, '!!str '): |
||
| 611 | $s = (string) substr($scalar, 6); |
||
| 612 | |||
| 613 | if (\in_array($s[0] ?? '', ['"', "'"], true)) { |
||
| 614 | $isQuotedString = true; |
||
| 615 | $s = self::parseQuotedScalar($s); |
||
| 616 | } |
||
| 617 | |||
| 618 | return $s; |
||
| 619 | case 0 === strpos($scalar, '! '): |
||
| 620 | return substr($scalar, 2); |
||
| 621 | case 0 === strpos($scalar, '!php/object'): |
||
| 622 | if (self::$objectSupport) { |
||
| 623 | if (!isset($scalar[12])) { |
||
| 624 | trigger_deprecation('symfony/yaml', '5.1', 'Using the !php/object tag without a value is deprecated.'); |
||
| 625 | |||
| 626 | return false; |
||
| 627 | } |
||
| 628 | |||
| 629 | return unserialize(self::parseScalar(substr($scalar, 12))); |
||
| 630 | } |
||
| 631 | |||
| 632 | if (self::$exceptionOnInvalidType) { |
||
| 633 | throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); |
||
| 634 | } |
||
| 635 | |||
| 636 | return null; |
||
| 637 | case 0 === strpos($scalar, '!php/const'): |
||
| 638 | if (self::$constantSupport) { |
||
| 639 | if (!isset($scalar[11])) { |
||
| 640 | trigger_deprecation('symfony/yaml', '5.1', 'Using the !php/const tag without a value is deprecated.'); |
||
| 641 | |||
| 642 | return ''; |
||
| 643 | } |
||
| 644 | |||
| 645 | $i = 0; |
||
| 646 | if (\defined($const = self::parseScalar(substr($scalar, 11), 0, null, $i, false))) { |
||
| 647 | return \constant($const); |
||
| 648 | } |
||
| 649 | |||
| 650 | throw new ParseException(sprintf('The constant "%s" is not defined.', $const), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); |
||
| 651 | } |
||
| 652 | if (self::$exceptionOnInvalidType) { |
||
| 653 | throw new ParseException(sprintf('The string "%s" could not be parsed as a constant. Did you forget to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); |
||
| 654 | } |
||
| 655 | |||
| 656 | return null; |
||
| 657 | case 0 === strpos($scalar, '!!float '): |
||
| 658 | return (float) substr($scalar, 8); |
||
| 659 | case 0 === strpos($scalar, '!!binary '): |
||
| 660 | return self::evaluateBinaryScalar(substr($scalar, 9)); |
||
| 661 | } |
||
| 662 | |||
| 663 | throw new ParseException(sprintf('The string "%s" could not be parsed as it uses an unsupported built-in tag.', $scalar), self::$parsedLineNumber, $scalar, self::$parsedFilename); |
||
| 664 | case preg_match('/^(?:\+|-)?0o(?P<value>[0-7_]++)$/', $scalar, $matches): |
||
| 665 | $value = str_replace('_', '', $matches['value']); |
||
| 666 | |||
| 667 | if ('-' === $scalar[0]) { |
||
| 668 | return -octdec($value); |
||
| 669 | } |
||
| 670 | |||
| 671 | return octdec($value); |
||
| 672 | case \in_array($scalar[0], ['+', '-', '.'], true) || is_numeric($scalar[0]): |
||
| 673 | if (Parser::preg_match('{^[+-]?[0-9][0-9_]*$}', $scalar)) { |
||
| 674 | $scalar = str_replace('_', '', $scalar); |
||
| 675 | } |
||
| 676 | |||
| 677 | switch (true) { |
||
| 678 | case ctype_digit($scalar): |
||
| 679 | if (preg_match('/^0[0-7]+$/', $scalar)) { |
||
| 680 | trigger_deprecation('symfony/yaml', '5.1', 'Support for parsing numbers prefixed with 0 as octal numbers. They will be parsed as strings as of 6.0. Use "%s" to represent the octal number.', '0o'.substr($scalar, 1)); |
||
| 681 | |||
| 682 | return octdec($scalar); |
||
| 683 | } |
||
| 684 | |||
| 685 | $cast = (int) $scalar; |
||
| 686 | |||
| 687 | return ($scalar === (string) $cast) ? $cast : $scalar; |
||
| 688 | case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)): |
||
| 689 | if (preg_match('/^-0[0-7]+$/', $scalar)) { |
||
| 690 | trigger_deprecation('symfony/yaml', '5.1', 'Support for parsing numbers prefixed with 0 as octal numbers. They will be parsed as strings as of 6.0. Use "%s" to represent the octal number.', '-0o'.substr($scalar, 2)); |
||
| 691 | |||
| 692 | return -octdec(substr($scalar, 1)); |
||
| 693 | } |
||
| 694 | |||
| 695 | $cast = (int) $scalar; |
||
| 696 | |||
| 697 | return ($scalar === (string) $cast) ? $cast : $scalar; |
||
| 698 | case is_numeric($scalar): |
||
| 699 | case Parser::preg_match(self::getHexRegex(), $scalar): |
||
| 700 | $scalar = str_replace('_', '', $scalar); |
||
| 701 | |||
| 702 | return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar; |
||
| 703 | case '.inf' === $scalarLower: |
||
| 704 | case '.nan' === $scalarLower: |
||
| 705 | return -log(0); |
||
| 706 | case '-.inf' === $scalarLower: |
||
| 707 | return log(0); |
||
| 708 | case Parser::preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar): |
||
| 709 | return (float) str_replace('_', '', $scalar); |
||
| 710 | case Parser::preg_match(self::getTimestampRegex(), $scalar): |
||
| 711 | try { |
||
| 712 | // When no timezone is provided in the parsed date, YAML spec says we must assume UTC. |
||
| 713 | $time = new \DateTime($scalar, new \DateTimeZone('UTC')); |
||
| 714 | } catch (\Exception $e) { |
||
| 715 | // Some dates accepted by the regex are not valid dates. |
||
| 716 | throw new ParseException(\sprintf('The date "%s" could not be parsed as it is an invalid date.', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename, $e); |
||
| 717 | } |
||
| 718 | |||
| 719 | if (Yaml::PARSE_DATETIME & $flags) { |
||
| 720 | return $time; |
||
| 721 | } |
||
| 722 | |||
| 723 | try { |
||
| 724 | if (false !== $scalar = $time->getTimestamp()) { |
||
| 725 | return $scalar; |
||
| 726 | } |
||
| 727 | } catch (\ValueError $e) { |
||
| 728 | // no-op |
||
| 729 | } |
||
| 730 | |||
| 731 | return $time->format('U'); |
||
| 732 | } |
||
| 733 | } |
||
| 734 | |||
| 735 | return (string) $scalar; |
||
| 736 | } |
||
| 737 | |||
| 738 | private static function parseTag(string $value, int &$i, int $flags): ?string |
||
| 776 | } |
||
| 777 | |||
| 778 | public static function evaluateBinaryScalar(string $scalar): string |
||
| 779 | { |
||
| 780 | $parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar)); |
||
| 781 | |||
| 782 | if (0 !== (\strlen($parsedBinaryData) % 4)) { |
||
| 783 | throw new ParseException(sprintf('The normalized base64 encoded data (data without whitespace characters) length must be a multiple of four (%d bytes given).', \strlen($parsedBinaryData)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); |
||
| 784 | } |
||
| 785 | |||
| 786 | if (!Parser::preg_match('#^[A-Z0-9+/]+={0,2}$#i', $parsedBinaryData)) { |
||
| 787 | throw new ParseException(sprintf('The base64 encoded data (%s) contains invalid characters.', $parsedBinaryData), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); |
||
| 788 | } |
||
| 789 | |||
| 790 | return base64_decode($parsedBinaryData, true); |
||
| 791 | } |
||
| 792 | |||
| 793 | private static function isBinaryString(string $value): bool |
||
| 794 | { |
||
| 795 | return !preg_match('//u', $value) || preg_match('/[^\x00\x07-\x0d\x1B\x20-\xff]/', $value); |
||
| 796 | } |
||
| 797 | |||
| 798 | /** |
||
| 799 | * Gets a regex that matches a YAML date. |
||
| 800 | * |
||
| 801 | * @see http://www.yaml.org/spec/1.2/spec.html#id2761573 |
||
| 802 | */ |
||
| 803 | private static function getTimestampRegex(): string |
||
| 806 | ~^ |
||
| 807 | (?P<year>[0-9][0-9][0-9][0-9]) |
||
| 808 | -(?P<month>[0-9][0-9]?) |
||
| 809 | -(?P<day>[0-9][0-9]?) |
||
| 810 | (?:(?:[Tt]|[ \t]+) |
||
| 811 | (?P<hour>[0-9][0-9]?) |
||
| 812 | :(?P<minute>[0-9][0-9]) |
||
| 813 | :(?P<second>[0-9][0-9]) |
||
| 814 | (?:\.(?P<fraction>[0-9]*))? |
||
| 815 | (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?) |
||
| 816 | (?::(?P<tz_minute>[0-9][0-9]))?))?)? |
||
| 817 | $~x |
||
| 818 | EOF; |
||
| 819 | } |
||
| 820 | |||
| 821 | /** |
||
| 822 | * Gets a regex that matches a YAML number in hexadecimal notation. |
||
| 823 | */ |
||
| 824 | private static function getHexRegex(): string |
||
| 827 | } |
||
| 828 | } |
||
| 829 |