private static function consumeLabel()

in src/unparsed-blocks/LinkReferenceDefinition.php [160:213]


  private static function consumeLabel(Lines $lines): ?(string, Lines) {
    list($column, $first_raw, $_) = $lines->getColumnFirstLineAndRest();
    list($_, $first, $_) = Lines::stripUpToNLeadingWhitespace(
      $first_raw,
      3,
      $column,
    );

    if (!Str\starts_with($first, '[')) {
      return null;
    }

    $label = '';
    $lines = $lines->withoutFirstNBytes((int)Str\search($first_raw, '[') + 1);

    while (!$lines->isEmpty()) {
      list($line, $rest) = $lines->getFirstLineAndRest();
      $len = Str\length($line);
      for ($i = 0; $i < $len; ++$i) {
        $char = $line[$i];
        if ($char === '[') {
          return null;
        }
        if ($char === ']') {
          break;
        }
        if ($char === "\\") {
          if ($i + 1 < $len) {
            $label .= "\\".$line[$i + 1];
            ++$i;
            continue;
          }
        }
        $label .= $char;
      }

      if ($i < $len) {
        // We matched the ']'
        $lines = $lines->withoutFirstNBytes($i + 1);
        break;
      }

      if ($rest->isEmpty()) {
        return null;
      }
      $lines = $rest;
    }

    if (Str\trim($label) === '') {
      return null;
    }

    return tuple($label, $lines);
  }