Skip to content

Instantly share code, notes, and snippets.

@carcinocron
Created December 4, 2019 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carcinocron/0b7e407616a156a24e799d72e53902e3 to your computer and use it in GitHub Desktop.
Save carcinocron/0b7e407616a156a24e799d72e53902e3 to your computer and use it in GitHub Desktop.
dump table in laravel phpunit or artisan tinker
<?php
namespace App\Console;
use Symfony\Component\Console\Helper\Table as SymfonyTable;
use Symfony\Component\Console\Output\StreamOutput;
class Table
{
static function dump ($headers, $rows = null) {
if ($rows === null) {
$rows = $headers;
$headers = null;
}
if (!$rows || count($rows) === 0) {
dump('no table data');
}
$output = new StreamOutput(fopen('php://stdout', 'w'));
$table = new SymfonyTable($output);
if ($headers === true) {
$table->setHeaders(array_keys($rows[0]));
} else if (is_array($headers) && count($headers) > 0) {
$table->setHeaders($headers);
}
$table->setRows($rows);
// writes to output
$table->render();
}
}
@carcinocron
Copy link
Author

php artisan tinker example:

>>> App\Console\Table::dump([[1,2],[3,4]]);
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
>>> App\Console\Table::dump(true, [[1,2],[3,4]]);
+---+---+
| 0 | 1 |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
=> null
>>> App\Console\Table::dump(['a', 'b'], [[1,2],[3,4]]);
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
=> null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment