Passed
Push — develop ( add880...26f5dd )
by nguereza
02:36
created

Table::render()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 41
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 28
nc 7
nop 2
dl 0
loc 41
rs 8.8497
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Platine Console
5
 *
6
 * Platine Console is a powerful library with support of custom
7
 * style to build command line interface applications
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Console
12
 * Copyright (c) 2017-2020 Jitendra Adhikari
13
 *
14
 * Permission is hereby granted, free of charge, to any person obtaining a copy
15
 * of this software and associated documentation files (the "Software"), to deal
16
 * in the Software without restriction, including without limitation the rights
17
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
 * copies of the Software, and to permit persons to whom the Software is
19
 * furnished to do so, subject to the following conditions:
20
 *
21
 * The above copyright notice and this permission notice shall be included in all
22
 * copies or substantial portions of the Software.
23
 *
24
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
 * SOFTWARE.
31
 */
32
33
/**
34
 *  @file Table.php
35
 *
36
 *  The Output Table class
37
 *
38
 *  @package    Platine\Console\Output
39
 *  @author Platine Developers Team
40
 *  @copyright  Copyright (c) 2020
41
 *  @license    http://opensource.org/licenses/MIT  MIT License
42
 *  @link   http://www.iacademy.cf
43
 *  @version 1.0.0
44
 *  @filesource
45
 */
46
47
declare(strict_types=1);
48
49
namespace Platine\Console\Output;
50
51
use Platine\Console\Exception\InvalidArgumentException;
52
use Platine\Console\Util\Helper;
53
54
/**
55
 * Class Table
56
 * @package Platine\Console\Output
57
 */
58
class Table
59
{
60
61
    /**
62
     * Render table data
63
     * @param array<int, array<int, string>> $rows
64
     * @param array<string, string> $styles
65
     * @return string
66
     */
67
    public function render(array $rows, array $styles = []): string
68
    {
69
        $table = $this->normalize($rows);
70
        if (empty($table)) {
71
            return '';
72
        }
73
74
        list($head, $tableRows) = $table;
75
        $normalizedStyles = $this->normalizeStyles($styles);
76
        $title = [];
77
        $dash = [];
78
        $body = [];
79
80
        list($start, $end) = $normalizedStyles['head'];
81
        foreach ($head as $col => $size) {
82
            $dash[] = str_repeat('-', (int) $size + 2);
83
            $title[] = str_pad(Helper::toWords($col), (int)$size, ' ');
84
        }
85
86
        $titleStr = '|' . $start . ' '
87
                . implode(' ' . $end . '|' . $start . ' ', $title)
88
                . ' ' . $end . '|' . PHP_EOL;
89
90
        $odd = true;
91
        foreach ($tableRows as $row) {
92
            $parts = [];
93
            list($start, $end) = $normalizedStyles[['even', 'odd'][(int) $odd]];
94
            foreach ($head as $col => $size) {
95
                $parts[] = str_pad(isset($row[$col]) ? $row[$col] : '', (int)$size, ' ');
96
            }
97
98
            $odd = !$odd;
0 ignored issues
show
introduced by
The condition $odd is always true.
Loading history...
99
            $body[] = '|' . $start . ' '
100
                    . implode(' ' . $end . '|' . $start . ' ', $parts)
101
                    . ' ' . $end . '|';
102
        }
103
104
        $dashStr = '+' . implode('+', $dash) . '+' . PHP_EOL;
105
        $bodyStr = implode(PHP_EOL, $body) . PHP_EOL;
106
107
        return $dashStr . $titleStr . $dashStr . $bodyStr . $dashStr;
108
    }
109
110
    /**
111
     * Normalize table data
112
     * @param array<int, array<int, mixed>> $rows
113
     * @return array<int, array<int, string>>
114
     */
115
    protected function normalize(array $rows): array
116
    {
117
        $head = reset($rows);
118
119
        if ($head === false || empty($head)) {
120
            return [];
121
        }
122
123
        if (!is_array($head)) {
124
            throw new InvalidArgumentException(sprintf(
125
                'Table rows must be an array of assoc arrays, [%s] given',
126
                gettype($head)
127
            ));
128
        }
129
130
        $header = array_fill_keys(array_keys($head), null);
131
        foreach ($rows as $i => &$row) {
132
            $row = array_merge($header, $row);
133
        }
134
135
        foreach ($header as $col => &$value) {
136
            $cols = array_column($rows, $col);
137
            $span = array_map('strlen', $cols);
138
            $span[] = strlen($col);
139
            $value = max($span);
140
        }
141
142
        return [$header, $rows];
143
    }
144
145
    /**
146
     * Normalize table styles
147
     * @param array<string, string> $styles
148
     * @return array<string, array<string>>
149
     */
150
    protected function normalizeStyles(array $styles): array
151
    {
152
        $default = [
153
            'head' => ['', ''],
154
            'odd' => ['', ''],
155
            'even' => ['', ''],
156
        ];
157
158
        foreach ($styles as $for => $style) {
159
            if (isset($default[$for])) {
160
                $default[$for] = ['<' . trim($style, '<> ') . '>', '</end>'];
161
            }
162
        }
163
164
        return $default;
165
    }
166
}
167