You are here

public static function EntityUpdatePrint::drushPrintTable in Entity Update 8

Same name and namespace in other branches
  1. 2.0.x src/EntityUpdatePrint.php \Drupal\entity_update\EntityUpdatePrint::drushPrintTable()

Print a table to drush terminal.

Parameters

array $table: The table to print.

2 calls to EntityUpdatePrint::drushPrintTable()
EntityCheck::getEntityList in src/EntityCheck.php
Get entity list.
EntityCheck::getEntityTypesList in src/EntityCheck.php
Get entity types list.

File

src/EntityUpdatePrint.php, line 67

Class

EntityUpdatePrint
EntityCheck CLI Print class.

Namespace

Drupal\entity_update

Code

public static function drushPrintTable(array $table) {

  // Check execution from CLI.
  if (php_sapi_name() != 'cli') {
    return;
  }
  $cols = exec('tput cols');
  $line_empty = "|" . str_repeat("-", $cols - 2) . "|";
  drush_print($line_empty);
  $header = empty($table['#header']) ? NULL : $table['#header'];
  $rows = empty($table['#rows']) ? NULL : $table['#rows'];

  // Calculate colones size.
  $csizes = [];
  if ($rows) {
    if ($header) {
      $rows['header'] = $header;
    }
    foreach ($rows as $row) {
      $idx = 0;
      foreach ($row as $txt) {
        if (empty($csizes[$idx]) || $csizes[$idx] < strlen($txt)) {
          $csizes[$idx] = strlen($txt);
        }
        $idx++;
      }
    }

    // Remove temporerly added header.
    if ($header) {
      unset($rows['header']);
    }
  }
  elseif ($header) {
    foreach ($header as $txt) {
      $csizes[] = strlen($txt);
    }
  }

  // Print caption.
  if (!empty($table['#caption'])) {
    $t = strlen($table['#caption']);
    if ($t < $cols - 2) {
      $line = str_repeat(" ", (int) ($cols - $t) / 2);
      $line = $line . $table['#caption'] . $line;
    }
    else {
      $line = $table['#caption'];
    }
    drush_print($line);
    drush_print($line_empty);
  }

  // Print header.
  if ($header) {
    $line = "|";
    $idx = 0;
    foreach ($header as $txt) {
      $line .= " " . $txt . str_repeat(" ", $csizes[$idx] - strlen($txt)) . "|";
      $idx++;
    }
    $line = substr($line, 0, $cols);
    drush_print($line);
    drush_print($line_empty);
  }

  // Print data.
  if ($rows) {
    foreach ($rows as $row) {
      $line = "|";
      $idx = 0;
      foreach ($row as $txt) {
        $line .= " " . $txt . str_repeat(" ", $csizes[$idx] - strlen($txt)) . "|";
        $idx++;
      }
      $line = substr($line, 0, $cols);
      drush_print($line);
    }
  }
  else {
    $txt = dt('No data to display');
    $t = strlen($txt);
    if ($t < $cols - 2) {
      $line = str_repeat(" ", (int) ($cols - $t) / 2);
      $line = $line . $txt . $line;
    }
    else {
      $line = $txt;
    }
    drush_print($line);
  }
  drush_print($line_empty);
}