From f0f33eebaf298bfc6053fe8d18c87f38211c2238 Mon Sep 17 00:00:00 2001 From: Jitendra Adhikari Date: Thu, 26 Dec 2019 19:10:52 +0700 Subject: [PATCH] refactor(writer): use Table::render instead --- src/Output/Writer.php | 86 +------------------------------------------ 1 file changed, 2 insertions(+), 84 deletions(-) diff --git a/src/Output/Writer.php b/src/Output/Writer.php index 31860c2..26c5d15 100644 --- a/src/Output/Writer.php +++ b/src/Output/Writer.php @@ -11,9 +11,6 @@ namespace Ahc\Cli\Output; -use Ahc\Cli\Exception\InvalidArgumentException; -use Ahc\Cli\Helper\InflectsString; - /** * Cli Writer. * @@ -161,8 +158,6 @@ */ class Writer { - use InflectsString; - /** @var resource Output file handle */ protected $stream; @@ -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, '<> ') . '>', '']; - } - } + $table = (new Table)->render($rows, $styles); - return $default; + return $this->colors($table); } /**