public static function consume()

in src/unparsed-blocks/TableExtension.php [28:123]


  public static function consume(
    Context $ctx,
    Lines $lines,
  ): ?(Block, Lines) {
    if ($ctx->isInParagraphContinuation()) {
      return null;
    }

    $rows = vec[];
    while (!$lines->isEmpty()) {
      $result = self::consumeRow($ctx, $lines);
      if ($result === null) {
        break;
      }
      list($definitely_row, $row, $lines) = $result;
      if (C\count($rows) < 2 && !$definitely_row) {
        return null;
      }
      $rows[] = $row;
    }

    if (C\count($rows) < 2) {
      return null;
    }
    $header = $rows[0];
    $delimiter = $rows[1];

    $column_count = C\count($header);
    if (C\count($delimiter) !== $column_count) {
      /* Valid:
       *
       *   foo|bar
       *   ---|---
       *
       * Invalid:
       *
       *   foo|bar
       *   ---|---|---
       *
       *   foo|bar|baz
       *   ---|---
       */
      return null;
    }

    $alignments = vec[];
    foreach ($delimiter as $col) {
      $left = Str\starts_with($col, ':');
      $right = Str\ends_with($col, ':');
      $col = Str\trim($col, ':');
      if (Str\length($col) === 0) {
        return null;
      }
      $col = Str\trim($col, '-');
      if (Str\length($col) !== 0) {
        return null;
      }

      $align = null;
      if ($left && $right) {
        $align = ColumnAlignment::CENTER;
      } else if ($left) {
        $align = ColumnAlignment::LEFT;
      } else if ($right) {
        $align = ColumnAlignment::RIGHT;
      }
      $alignments[] = $align;
    }

    $data = vec[];
    foreach (Vec\drop($rows, 2) as $row) {
      $count = C\count($row);
      if ($count === $column_count) {
        $data[] = $row;
        continue;
      }
      if ($count > $column_count) {
        $data[] = Vec\take($row, $column_count);
        continue;
      }
      invariant($count < $column_count, 'should have `continue;`-d');
      $data[] = Vec\concat(
        $row,
        Vec\fill($column_count - $count, ''),
      );
    }

    return tuple(
      new self(
        $header,
        $alignments,
        $data,
      ),
      $lines,
    );
  }