Issues (10)

src/Output/Table.php (1 issue)

Severity
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   https://www.platine-php.com
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
     * Render table data
62
     * @param array<int, array<int, array<string, string>>> $rows
63
     * @param array<string, string> $styles
64
     * @return string
65
     */
66
    public function render(array $rows, array $styles = []): string
67
    {
68
        $normalizedTable = $this->normalize($rows);
69
        if (count($normalizedTable) === 0) {
70
            return '';
71
        }
72
73
        /** @var array<string, int> $head */
74
        $head = $normalizedTable['header'];
75
76
        /** @var array<int, array<string, string>> $tableRows */
77
        $tableRows = $normalizedTable['rows'];
78
79
        $normalizedStyles = $this->normalizeStyles($styles);
80
        $title = [];
81
        $dash = [];
82
        $body = [];
83
84
        list($start, $end) = $normalizedStyles['head'];
85
        /** @var string $col */
86
        /** @var int $size */
87
        foreach ($head as $col => $size) {
88
            $dash[] = str_repeat('-', $size + 2);
89
            $title[] = str_pad(Helper::toWords($col), $size, ' ');
90
        }
91
92
        $titleStr = '|' . $start . ' '
93
                . implode(' ' . $end . '|' . $start . ' ', $title)
94
                . ' ' . $end . '|' . PHP_EOL;
95
96
        $odd = true;
97
        foreach ($tableRows as /** @var array<int, array<string, string>> $row */ $row) {
98
            $parts = [];
99
            list($start, $end) = $normalizedStyles[['even', 'odd'][(int) $odd]];
100
            /** @var string $col */
101
            /** @var int $size */
102
            foreach ($head as $col => $size) {
103
                $parts[] = str_pad(isset($row[$col]) ? $row[$col] : '', $size, ' ');
104
            }
105
106
            $odd = !$odd;
0 ignored issues
show
The condition $odd is always true.
Loading history...
107
            $body[] = '|' . $start . ' '
108
                    . implode(' ' . $end . '|' . $start . ' ', $parts)
109
                    . ' ' . $end . '|';
110
        }
111
112
        $dashStr = '+' . implode('+', $dash) . '+' . PHP_EOL;
113
        $bodyStr = implode(PHP_EOL, $body) . PHP_EOL;
114
115
        return $dashStr . $titleStr . $dashStr . $bodyStr . $dashStr;
116
    }
117
118
    /**
119
     * Normalize table data
120
     * @param array<int, array<mixed>|mixed> $rows
121
     * @return array<string, array<mixed>>
122
     */
123
    protected function normalize(array $rows): array
124
    {
125
        $head = reset($rows);
126
127
        if ($head === false) {
128
            return [];
129
        }
130
131
        if (!is_array($head)) {
132
            throw new InvalidArgumentException(sprintf(
133
                'Table rows must be an array of assoc arrays, [%s] given',
134
                gettype($head)
135
            ));
136
        }
137
138
        if (count($head) === 0) {
139
            return [];
140
        }
141
142
        $header = array_fill_keys(array_keys($head), null);
143
        foreach ($rows as &$row) {
144
            $row = array_merge($header, $row);
145
        }
146
147
        /** @var array<string, string> $header */
148
        foreach ($header as $col => &$value) {
149
            /** @var array<string> $cols */
150
            $cols = array_column($rows, $col);
151
            $span = array_map(fn($a) => strlen($a), $cols);
152
            $span[] = strlen($col);
153
            $value = max($span);
154
        }
155
156
        return [
157
            'header' => $header,
158
            'rows' => $rows
159
        ];
160
    }
161
162
    /**
163
     * Normalize table styles
164
     * @param array<string, string> $styles
165
     * @return array<string, array<string>>
166
     */
167
    protected function normalizeStyles(array $styles): array
168
    {
169
        $default = [
170
            'head' => ['', ''],
171
            'odd' => ['', ''],
172
            'even' => ['', ''],
173
        ];
174
175
        foreach ($styles as $for => $style) {
176
            if (isset($default[$for])) {
177
                $default[$for] = ['<' . trim($style, '<> ') . '>', '</end>'];
178
            }
179
        }
180
181
        return $default;
182
    }
183
}
184