Skip to content

Commit

Permalink
refactor(writer): use Table::render instead
Browse files Browse the repository at this point in the history
  • Loading branch information
adhocore committed Dec 26, 2019
1 parent 808e80e commit f0f33ee
Showing 1 changed file with 2 additions and 84 deletions.
86 changes: 2 additions & 84 deletions src/Output/Writer.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@

namespace Ahc\Cli\Output;

use Ahc\Cli\Exception\InvalidArgumentException;
use Ahc\Cli\Helper\InflectsString;

/**
* Cli Writer.
*
Expand Down Expand Up @@ -161,8 +158,6 @@
*/
class Writer
{
use InflectsString;

/** @var resource Output file handle */
protected $stream;

Expand Down Expand Up @@ -291,86 +286,9 @@ public function raw($text, bool $error = false): self
*/
public function table(array $rows, array $styles = []): self
{
if ([] === $table = $this->normalizeTable($rows)) {
return $this;
}

list($head, $rows) = $table;

$styles = $this->normalizeStyles($styles);
$title = $body = $dash = [];

list($start, $end) = $styles['head'];
foreach ($head as $col => $size) {
$dash[] = \str_repeat('-', $size + 2);
$title[] = \str_pad($this->toWords($col), $size, ' ');
}

$title = "|$start " . \implode(" $end|$start ", $title) . " $end|" . \PHP_EOL;

$odd = true;
foreach ($rows as $row) {
$parts = [];

list($start, $end) = $styles[['even', 'odd'][(int) $odd]];
foreach ($head as $col => $size) {
$parts[] = \str_pad($row[$col] ?? '', $size, ' ');
}

$odd = !$odd;
$body[] = "|$start " . \implode(" $end|$start ", $parts) . " $end|";
}

$dash = '+' . \implode('+', $dash) . '+' . \PHP_EOL;
$body = \implode(\PHP_EOL, $body) . \PHP_EOL;

return $this->colors("$dash$title$dash$body$dash");
}

protected function normalizeTable(array $rows): array
{
$head = \reset($rows);
if (empty($head)) {
return [];
}

if (!\is_array($head)) {
throw new InvalidArgumentException(
\sprintf('Rows must be array of assoc arrays, %s given', \gettype($head))
);
}

$head = \array_fill_keys(\array_keys($head), null);
foreach ($rows as $i => &$row) {
$row = \array_merge($head, $row);
}

foreach ($head as $col => &$value) {
$cols = \array_column($rows, $col);
$span = \array_map('strlen', $cols);
$span[] = \strlen($col);
$value = \max($span);
}

return [$head, $rows];
}

protected function normalizeStyles(array $styles)
{
$default = [
// styleFor => ['styleStartFn', 'end']
'head' => ['', ''],
'odd' => ['', ''],
'even' => ['', ''],
];

foreach ($styles as $for => $style) {
if (isset($default[$for])) {
$default[$for] = ['<' . \trim($style, '<> ') . '>', '</end>'];
}
}
$table = (new Table)->render($rows, $styles);

return $default;
return $this->colors($table);
}

/**
Expand Down

0 comments on commit f0f33ee

Please sign in to comment.