Skip to content

Commit

Permalink
Add multiline support
Browse files Browse the repository at this point in the history
  • Loading branch information
viossat committed Mar 13, 2019
1 parent 51aaac6 commit 8e5b683
Showing 1 changed file with 32 additions and 8 deletions.
40 changes: 32 additions & 8 deletions src/ArrayToTextTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ public function getTable($data = null) {
$keysRow = array_combine($this->keys, $this->keys);
if ($this->upperKeys)
$keysRow = array_map('mb_strtoupper', $keysRow);
$table .= $i . $this->row($keysRow, $this->keysAlignment) . PHP_EOL;
$table .= $i . implode(PHP_EOL, $this->row($keysRow, $this->keysAlignment)) . PHP_EOL;

$table .= $i . $this->line($d->getVerticalRight(), $d->getHorizontal(), $d->getCross(), $d->getVerticalLeft()) . PHP_EOL;
}

foreach ($data as $row)
$table .= $i . $this->row($row, $this->valuesAlignment) . PHP_EOL;
$table .= $i . implode(PHP_EOL, $this->row($row, $this->valuesAlignment)) . PHP_EOL;

$table .= $i . $this->line($d->getBottomLeft(), $d->getHorizontal(), $d->getHorizontalUp(), $d->getBottomRight()) . PHP_EOL;

Expand Down Expand Up @@ -177,12 +177,30 @@ protected function line($left, $horizontal, $link, $right) {
}

protected function row($row, $alignment) {
$line = $this->decorator->getVertical();
$data = [];
$height = 1;
foreach ($this->keys as $key) {
$value = isset($row[$key]) ? $row[$key] : '';
$line .= ' ' . static::mb_str_pad($value, $this->widths[$key], ' ', $alignment) . ' ' . $this->decorator->getVertical();
$data[$key] = isset($row[$key]) ? static::valueToLines($row[$key]) : [''];
$height = max($height, count($data[$key]));
}

$rowLines = [];
for ($i = 0; $i < $height; $i++) {
$rowLine = [];
foreach ($data as $key => $value)
$rowLine[$key] = isset($value[$i]) ? $value[$i] : '';
$rowLines[] = $this->rowLine($rowLine, $alignment);
}

return $rowLines;
}

protected function rowLine($row, $alignment) {
$line = $this->decorator->getVertical();

foreach ($row as $key => $value)
$line .= ' ' . static::mb_str_pad($value, $this->widths[$key], ' ', $alignment) . ' ' . $this->decorator->getVertical();

if (empty($row))
$line .= $this->decorator->getVertical();

Expand Down Expand Up @@ -223,9 +241,15 @@ protected function setWidth($key, $value) {
if (!isset($this->widths[$key]))
$this->widths[$key] = 0;

$width = mb_strlen($value) + $this->countCJK($value);
if ($width > $this->widths[$key])
$this->widths[$key] = $width;
foreach (static::valueToLines($value) as $line) {
$width = mb_strlen($line) + $this->countCJK($line);
if ($width > $this->widths[$key])
$this->widths[$key] = $width;
}
}

protected static function valueToLines($value) {
return explode("\n", $value);
}

protected static function mb_str_pad($input, $pad_length, $pad_string = ' ', $pad_type = STR_PAD_RIGHT, $encoding = null) {
Expand Down

0 comments on commit 8e5b683

Please sign in to comment.