You are here

public function TableTagPlugin::buildElement in Extensible BBCode 8.3

Same name and namespace in other branches
  1. 4.0.x standard/src/Plugin/XBBCode/TableTagPlugin.php \Drupal\xbbcode_standard\Plugin\XBBCode\TableTagPlugin::buildElement()

Build a render array from the tag.

Parameters

\Drupal\xbbcode\Parser\Tree\TagElementInterface $tag: The tag element in the parse tree.

Return value

array The render array.

Overrides RenderTagPlugin::buildElement

File

standard/src/Plugin/XBBCode/TableTagPlugin.php, line 36

Class

TableTagPlugin
Renders a table.

Namespace

Drupal\xbbcode_standard\Plugin\XBBCode

Code

public function buildElement(TagElementInterface $tag) : array {
  $element['#type'] = 'table';
  if ($caption = $tag
    ->getAttribute('caption')) {
    $element['#caption'] = $caption;
  }
  $alignments = [];
  if ($header = $tag
    ->getAttribute('header') ?: $tag
    ->getOption()) {

    /** @var string[] $headers */
    $headers = self::tabulateText($header)[0] ?: [
      $header,
    ];
    foreach ($headers as $i => $cell) {

      // Check if the label starts with an alignment symbol.
      if ($cell && array_key_exists($cell[0], self::ALIGNMENT)) {
        $alignments[$i] = self::ALIGNMENT[$cell[0]];
        $headers[$i] = substr($cell, 1);
      }
      else {

        // Trim leading whitespace.
        $headers[$i] = ltrim($cell);
        $alignments[$i] = NULL;
      }
    }
    if (implode('', $headers)) {
      $element['#header'] = $headers;
    }
  }
  foreach (static::tabulateTree($tag
    ->getChildren()) as $i => $row) {
    foreach ($row as $j => $cell) {
      $content = $cell
        ->getContent();

      // If not explicitly aligned, auto-align numeric strings.
      if (!isset($alignments[$j])) {
        $alignments[$j] = '';
      }
      $align = $alignments[$j] ?: (is_numeric($content) ? 'right' : NULL);
      $element["row-{$i}"][$j] = [
        '#markup' => Markup::create($content),
        '#wrapper_attributes' => $align ? [
          'style' => [
            'text-align:' . $align,
          ],
        ] : NULL,
      ];
    }
  }
  return $element;
}