Giter VIP home page Giter VIP logo

console-table's Introduction

PHP ConsoleTable

ConsoleTabe makes you easy to build console style tables. It helps you to display tabular data in terminal/shell. This is a component of PHPLucidFrame.

License: MIT

Composer Installation

composer require phplucidframe/console-table

Example 1: Bordered Table (Default)

require 'src/LucidFrame/Console/ConsoleTable.php';

$table = new LucidFrame\Console\ConsoleTable();
$table
    ->addHeader('Language')
    ->addHeader('Year')
    ->addRow()
        ->addColumn('PHP')
        ->addColumn(1994)
    ->addRow()
        ->addColumn('C++')
        ->addColumn(1983)
    ->addRow()
        ->addColumn('C')
        ->addColumn(1970)
    ->display()
;

You can also print the table using getTable method such as echo $table->getTable();

Output:

+----------+------+
| Language | Year |
+----------+------+
| PHP      | 1994 |
| C++      | 1983 |
| C        | 1970 |
+----------+------+

Example 2: Bordered Table with Padding Width 2

You can also use setHeaders() and addRow with Arrays.

require 'src/LucidFrame/Console/ConsoleTable.php';

$table = new LucidFrame\Console\ConsoleTable();
$table
    ->setHeaders(array('Language', 'Year'))
    ->addRow(array('PHP', 1994))
    ->addRow(array('C++', 1983))
    ->addRow(array('C', 1970))
    ->setPadding(2)
    ->display()
;

Output:

+------------+--------+
|  Language  |  Year  |
+------------+--------+
|  PHP       |  1994  |
|  C++       |  1983  |
|  C         |  1970  |
+------------+--------+

Example 3: Bordered Table with Left Margin Width 4

require 'src/LucidFrame/Console/ConsoleTable.php';

$table = new LucidFrame\Console\ConsoleTable();
$table
    ->setHeaders(array('Language', 'Year'))
    ->addRow(array('PHP', 1994))
    ->addRow(array('C++', 1983))
    ->addRow(array('C', 1970))
    ->setIndent(4)
    ->display()
;

Output:

    +----------+------+
    | Language | Year |
    +----------+------+
    | PHP      | 1994 |
    | C++      | 1983 |
    | C        | 1970 |
    +----------+------+

Example 4: Non-bordered Table with Header

require 'src/LucidFrame/Console/ConsoleTable.php';

$table = new LucidFrame\Console\ConsoleTable();
$table
    ->setHeaders(array('Language', 'Year'))
    ->addRow(array('PHP', 1994))
    ->addRow(array('C++', 1983))
    ->addRow(array('C', 1970))
    ->hideBorder()
    ->display()
;

Output:

 Language  Year
----------------
 PHP       1994
 C++       1983
 C         1970

Example 5: Non-bordered Table without Header

require 'src/LucidFrame/Console/ConsoleTable.php';

$table = new LucidFrame\Console\ConsoleTable();
$table
    ->addRow(array('PHP', 1994))
    ->addRow(array('C++', 1983))
    ->addRow(array('C', 1970))
    ->hideBorder()
    ->display()
;

Output:

 PHP  1994
 C++  1983
 C    1970

Example 6: Table with all borders

require 'src/LucidFrame/Console/ConsoleTable.php';

$table = new LucidFrame\Console\ConsoleTable();
$table
    ->setHeaders(array('Language', 'Year'))
    ->addRow(array('PHP', 1994))
    ->addRow(array('C++', 1983))
    ->addRow(array('C', 1970))
    ->showAllBorders()
    ->display()
;

Alternatively, you can use addBorderLine() for each row.

$table
    ->setHeaders(array('Language', 'Year'))
    ->addRow(array('PHP', 1994))
    ->addBorderLine()
    ->addRow(array('C++', 1983))
    ->addBorderLine()
    ->addRow(array('C', 1970))
    ->display()
;

Output

+----------+------+
| Language | Year |
+----------+------+
| PHP      | 1994 |
+----------+------+
| C++      | 1983 |
+----------+------+
| C        | 1970 |
+----------+------+

Test

If you have PHPUnit installed in your machine, you can run test at your project root.

composer install
phpunit tests

If you don't have PHPUnit, you can simply run this in your terminal.

php example.php

console-table's People

Contributors

dblencowe avatar dev-sithu avatar i-amdroid avatar pitsolu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

console-table's Issues

Warnings on empty table

if no rows :

PHP Notice:  Undefined offset: 0 in /home/david/dev/projects/search-engine/vendor/phplucidframe/console-table/src/LucidFrame/Console/ConsoleTable.php on line 238
PHP Warning:  count(): Parameter must be an array or an object that implements Countable in /home/david/dev/projects/search-engine/vendor/phplucidframe/console-table/src/LucidFrame/Console/ConsoleTable.php on line 238
PHP Notice:  Undefined offset: 0 in /home/david/dev/projects/search-engine/vendor/phplucidframe/console-table/src/LucidFrame/Console/ConsoleTable.php on line 238
PHP Warning:  count(): Parameter must be an array or an object that implements Countable in /home/david/dev/projects/search-engine/vendor/phplucidframe/console-table/src/LucidFrame/Console/ConsoleTable.php on line 238
PHP Notice:  Undefined offset: 0 in /home/david/dev/projects/search-engine/vendor/phplucidframe/console-table/src/LucidFrame/Console/ConsoleTable.php on line 238
PHP Warning:  count(): Parameter must be an array or an object that implements Countable in /home/david/dev/projects/search-engine/vendor/phplucidframe/console-table/src/LucidFrame/Console/ConsoleTable.php on line 238

Using terminal colors ( \033[0m ) breaks alignment

Hi,
First, thank you for this code !
If you use terminal colors / text decoration
for example:

echo "\033[44m\033[7mHi\033[0m";

the table alignment is broken
This is probably due to strlen($col) in calculateColumnWidth function, counting everything in the string, wich end up not printed on cli.

You should remove every extra caracters before counting string lengh,
with for example

$test = preg_replace('#\x1b[[][^A-Za-z]*[A-Za-z]#', '', $test);

(found here: https://stackoverflow.com/questions/40731273/php-remove-terminal-codes-from-string)

Request: One line array to table wrapper function

Any chance we could put something akin to this as a function?

function table_me($table_data ) {
	$table = new LucidFrame\Console\ConsoleTable();
	$table->addHeader(array_keys($table_data[0]));
	foreach ($table_data as $row) { 
		$table->addRow(@array_values($row));
	}
	$table->display();
}

That could give an one-liner method to produce a table form an associative array.

Cell width problem on multibyte characters

Hi!

First of all this package is awesome, i really like it so thanks for it!

I found an error on multibyte characters. I've listed records from a database table and there was some Hungarian names.

I fixed this with mb_strlen() and a new strPadUnicode method.
Here is the new method with the two fixed methods.

  /**
    * Calculate maximum width of each column
    *
    * @return array
    */
   private function calculateColumnWidth()
   {
       foreach ($this->data as $y => $row) {
           if (is_array($row)) {
               foreach ($row as $x => $col) {
                   $content = preg_replace('#\x1b[[][^A-Za-z]*[A-Za-z]#', '', $col);
                   if (!isset($this->columnWidths[$x])) {
                       $this->columnWidths[$x] = mb_strlen($content, 'UTF-8');
                   } else {
                       if (mb_strlen($content, 'UTF-8') > $this->columnWidths[$x]) {
                           $this->columnWidths[$x] = mb_strlen($content, 'UTF-8');
                       }
                   }
               }
           }
       }

       return $this->columnWidths;
   }

   /**
    * Get the printable cell content
    *
    * @param integer $index The column index
    * @param array   $row   The table row
    * @return string
    */
   private function getCellOutput($index, $row = null)
   {
       $cell = $row ? $row[$index] : '-';
       $width = $this->columnWidths[$index];
       $pad = $row ? $width - mb_strlen($cell, 'UTF-8') : $width;
       $padding = str_repeat($row ? ' ' : '-', $this->padding);

       $output = '';

       if ($index === 0) {
           $output .= str_repeat(' ', $this->indent);
       }

       if ($this->border) {
           $output .= $row ? '|' : '+';
       }

       $output .= $padding; # left padding
       $cell = trim(preg_replace('/\s+/', ' ', $cell)); # remove line breaks
       $content = preg_replace('#\x1b[[][^A-Za-z]*[A-Za-z]#', '', $cell);
       $delta = mb_strlen($cell, 'UTF-8') - mb_strlen($content, 'UTF-8');
       $output .= $this->strPadUnicode($cell, $width + $delta, $row ? ' ' : '-'); # cell content
       $output .= $padding; # right padding
       if ($row && $index == count($row) - 1 && $this->border) {
           $output .= $row ? '|' : '+';
       }

       return $output;
   }

   /**
    * Multibyte version of str_pad() function
    * @source http://php.net/manual/en/function.str-pad.php
    */
   private function strPadUnicode($str, $padLength, $padString = ' ', $dir = STR_PAD_RIGHT)
   {
       $strLen = mb_strlen($str, 'UTF-8');
       $padStrLen = mb_strlen($padString, 'UTF-8');
       if (!$strLen && ($dir == STR_PAD_RIGHT || $dir == STR_PAD_LEFT)) {
           $strLen = 1;
       }
       if (!$padLength || !$padStrLen || $padLength <= $strLen) {
           return $str;
       }

       $result = null;
       $repeat = ceil($strLen - $padStrLen + $padLength);
       if ($dir == STR_PAD_RIGHT) {
           $result = $str . str_repeat($padString, $repeat);
           $result = mb_substr($result, 0, $padLength, 'UTF-8');
       } else if ($dir == STR_PAD_LEFT) {
           $result = str_repeat($padString, $repeat) . $str;
           $result = mb_substr($result, -$padLength, null, 'UTF-8');
       } else if ($dir == STR_PAD_BOTH) {
           $length = ($padLength - $strLen) / 2;
           $repeat = ceil($length / $padStrLen);
           $result = mb_substr(str_repeat($padString, $repeat), 0, floor($length), 'UTF-8')
               . $str
               . mb_substr(str_repeat($padString, $repeat), 0, ceil($length), 'UTF-8');
       }

       return $result;
   }

With this fix everything is work great for me!

Thanks,
Frank Szklenár

how to set column size

i need to occupy a demarcated space and to occupy all the space i need to be able to set the column size

Wrong spacing with emojis

Hi !
Thanks you for this library but there is an issue with emojis in general 😄📚.

Code that breaks

<?php
require_once __DIR__ . "/../vendor/autoload.php";

$table = new LucidFrame\Console\ConsoleTable();
$table = $table
  ->addHeader("A")
  ->addHeader("B")
  ->addRow()
    ->addColumn("📚")
    ->addColumn("Hello")
  ->addRow()
    ->addColumn("X")
    ->addColumn("Foo Bared")
  ->display();

Expected behavior:

image

Actual behavior:

image

Environment

Shell: fish 3.3.1
PHP 8.0.12 (cli)
phplucidframe/console-table: ^1.2

Issue with non-autoresizing headers

Actual behavior

+----+------+-----+--------+------------+---+
| ID | Name | Key | Status | Page count |
+----+------+-----+--------+------------+---+
| 12345689  | Kategória szövege sok-sok betű | CK         | 12365478  | global | CURRENT 
+----+------+-----+--------+------------+---+

As you see, the header fixes to the size of the header string and does not autosize to the content. It contains utf8 characters but I had an issue with strings without multibyte characters, but even if it would handle multibyte strings badly the name column should wider than 5 chars.

Code:

  $ctable = new LucidFrame\Console\ConsoleTable();
  $ctable = $ctable->setHeaders(['ID', 'Name', 'Key', 'Status', 'Page count']);
  foreach($spaces as $row) {
    $ctable->addRow($row);
  }

  $ctable->display();

phplucidframe/console-table dev-master a973d91 Console Table

Does not support line feed

      ->addRow()
      ->addColumn("asdfasddasfdasf\nasdfsadfasdfasd\n")
      ->addColumn('12312312');

yields

| Original                         | Proposed |
+----------------------------------+----------+
| asdfasddasfdasf
asdfsadfasdfasd
 | 12312312 |
| asdfasddasfdasf
asdfsadfasdfasd
 | 12312312 |
| asdfasddasfdasf
asdfsadfasdfasd

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.