Passed
Pull Request — master (#19908)
by Rutger
08:15
created

Table   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 366
Duplicated Lines 0 %

Test Coverage

Coverage 99.32%

Importance

Changes 0
Metric Value
eloc 181
dl 0
loc 366
ccs 146
cts 147
cp 0.9932
rs 8.48
c 0
b 0
f 0
wmc 49

11 Methods

Rating   Name   Duplication   Size   Complexity  
A setHeaders() 0 4 1
A getScreenWidth() 0 9 3
A setScreenWidth() 0 4 1
B calculateRowsSize() 0 47 11
C renderRow() 0 47 12
A setChars() 0 4 1
A renderSeparator() 0 11 3
A setListPrefix() 0 4 1
A run() 0 44 5
A setRows() 0 12 4
B calculateRowHeight() 0 18 7

How to fix   Complexity   

Complex Class

Complex classes like Table often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Table, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\console\widgets;
9
10
use Yii;
11
use yii\base\Widget;
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\Console;
14
15
/**
16
 * Table class displays a table in console.
17
 *
18
 * For example,
19
 *
20
 * ```php
21
 * $table = new Table();
22
 *
23
 * echo $table
24
 *     ->setHeaders(['test1', 'test2', 'test3'])
25
 *     ->setRows([
26
 *         ['col1', 'col2', 'col3'],
27
 *         ['col1', 'col2', ['col3-0', 'col3-1', 'col3-2']],
28
 *     ])
29
 *     ->run();
30
 * ```
31
 *
32
 * or
33
 *
34
 * ```php
35
 * echo Table::widget([
36
 *     'headers' => ['test1', 'test2', 'test3'],
37
 *     'rows' => [
38
 *         ['col1', 'col2', 'col3'],
39
 *         ['col1', 'col2', ['col3-0', 'col3-1', 'col3-2']],
40
 *     ],
41
 * ]);
42
 *
43
 * @property-write string $listPrefix List prefix.
44
 * @property-write int $screenWidth Screen width.
45
 *
46
 * @author Daniel Gomez Pan <[email protected]>
47
 * @since 2.0.13
48
 */
49
class Table extends Widget
50
{
51
    const DEFAULT_CONSOLE_SCREEN_WIDTH = 120;
52
    const CONSOLE_SCROLLBAR_OFFSET = 3;
53
    const CHAR_TOP = 'top';
54
    const CHAR_TOP_MID = 'top-mid';
55
    const CHAR_TOP_LEFT = 'top-left';
56
    const CHAR_TOP_RIGHT = 'top-right';
57
    const CHAR_BOTTOM = 'bottom';
58
    const CHAR_BOTTOM_MID = 'bottom-mid';
59
    const CHAR_BOTTOM_LEFT = 'bottom-left';
60
    const CHAR_BOTTOM_RIGHT = 'bottom-right';
61
    const CHAR_LEFT = 'left';
62
    const CHAR_LEFT_MID = 'left-mid';
63
    const CHAR_MID = 'mid';
64
    const CHAR_MID_MID = 'mid-mid';
65
    const CHAR_RIGHT = 'right';
66
    const CHAR_RIGHT_MID = 'right-mid';
67
    const CHAR_MIDDLE = 'middle';
68
69
    /**
70
     * @var array table headers
71
     * @since 2.0.19
72
     */
73
    protected $headers = [];
74
    /**
75
     * @var array table rows
76
     * @since 2.0.19
77
     */
78
    protected $rows = [];
79
    /**
80
     * @var array table chars
81
     * @since 2.0.19
82
     */
83
    protected $chars = [
84
        self::CHAR_TOP => '═',
85
        self::CHAR_TOP_MID => '╤',
86
        self::CHAR_TOP_LEFT => '╔',
87
        self::CHAR_TOP_RIGHT => '╗',
88
        self::CHAR_BOTTOM => '═',
89
        self::CHAR_BOTTOM_MID => '╧',
90
        self::CHAR_BOTTOM_LEFT => '╚',
91
        self::CHAR_BOTTOM_RIGHT => '╝',
92
        self::CHAR_LEFT => '║',
93
        self::CHAR_LEFT_MID => '╟',
94
        self::CHAR_MID => '─',
95
        self::CHAR_MID_MID => '┼',
96
        self::CHAR_RIGHT => '║',
97
        self::CHAR_RIGHT_MID => '╢',
98
        self::CHAR_MIDDLE => '│',
99
    ];
100
    /**
101
     * @var array table column widths
102
     * @since 2.0.19
103
     */
104
    protected $columnWidths = [];
105
    /**
106
     * @var int screen width
107
     * @since 2.0.19
108
     */
109
    protected $screenWidth;
110
    /**
111
     * @var string list prefix
112
     * @since 2.0.19
113
     */
114
    protected $listPrefix = '• ';
115
116
117
    /**
118
     * Set table headers.
119
     *
120
     * @param array $headers table headers
121
     * @return $this
122
     */
123 22
    public function setHeaders(array $headers)
124
    {
125 22
        $this->headers = array_values($headers);
126 22
        return $this;
127
    }
128
129
    /**
130
     * Set table rows.
131
     *
132
     * @param array $rows table rows
133
     * @return $this
134
     */
135 23
    public function setRows(array $rows)
136
    {
137
        $this->rows = array_map(function($row) {
138
            return array_map(function($value) {
139 22
                return empty($value) && !is_numeric($value)
140 6
                    ? ' '
141 21
                    :  (is_array($value)
142 9
                        ? array_values($value)
143 22
                        : $value);
144 22
            }, array_values($row));
145 23
        }, $rows);
146 23
        return $this;
147
    }
148
149
    /**
150
     * Set table chars.
151
     *
152
     * @param array $chars table chars
153
     * @return $this
154
     */
155 1
    public function setChars(array $chars)
156
    {
157 1
        $this->chars = $chars;
158 1
        return $this;
159
    }
160
161
    /**
162
     * Set screen width.
163
     *
164
     * @param int $width screen width
165
     * @return $this
166
     */
167 21
    public function setScreenWidth($width)
168
    {
169 21
        $this->screenWidth = $width;
170 21
        return $this;
171
    }
172
173
    /**
174
     * Set list prefix.
175
     *
176
     * @param string $listPrefix list prefix
177
     * @return $this
178
     */
179 1
    public function setListPrefix($listPrefix)
180
    {
181 1
        $this->listPrefix = $listPrefix;
182 1
        return $this;
183
    }
184
185
    /**
186
     * @return string the rendered table
187
     */
188 23
    public function run()
189
    {
190 23
        $this->calculateRowsSize();
191 23
        $headerCount = count($this->headers);
192
193 23
        $buffer = $this->renderSeparator(
194 23
            $this->chars[self::CHAR_TOP_LEFT],
195 23
            $this->chars[self::CHAR_TOP_MID],
196 23
            $this->chars[self::CHAR_TOP],
197 23
            $this->chars[self::CHAR_TOP_RIGHT]
198
        );
199
        // Header
200 23
        if ($headerCount > 0) {
201 22
            $buffer .= $this->renderRow($this->headers,
202 22
                $this->chars[self::CHAR_LEFT],
203 22
                $this->chars[self::CHAR_MIDDLE],
204 22
                $this->chars[self::CHAR_RIGHT]
205
            );
206
        }
207
208
        // Content
209 23
        foreach ($this->rows as $i => $row) {
210 22
            if ($i > 0 || $headerCount > 0) {
211 22
                $buffer .= $this->renderSeparator(
212 22
                    $this->chars[self::CHAR_LEFT_MID],
213 22
                    $this->chars[self::CHAR_MID_MID],
214 22
                    $this->chars[self::CHAR_MID],
215 22
                    $this->chars[self::CHAR_RIGHT_MID]
216
                );
217
            }
218 22
            $buffer .= $this->renderRow($row,
219 22
                $this->chars[self::CHAR_LEFT],
220 22
                $this->chars[self::CHAR_MIDDLE],
221 22
                $this->chars[self::CHAR_RIGHT]);
222
        }
223
224 23
        $buffer .= $this->renderSeparator(
225 23
            $this->chars[self::CHAR_BOTTOM_LEFT],
226 23
            $this->chars[self::CHAR_BOTTOM_MID],
227 23
            $this->chars[self::CHAR_BOTTOM],
228 23
            $this->chars[self::CHAR_BOTTOM_RIGHT]
229
        );
230
231 23
        return $buffer;
232
    }
233
234
    /**
235
     * Renders a row of data into a string.
236
     *
237
     * @param array $row row of data
238
     * @param string $spanLeft character for left border
239
     * @param string $spanMiddle character for middle border
240
     * @param string $spanRight character for right border
241
     * @return string
242
     * @see \yii\console\widgets\Table::render()
243
     */
244 23
    protected function renderRow(array $row, $spanLeft, $spanMiddle, $spanRight)
245
    {
246 23
        $size = $this->columnWidths;
247
248 23
        $buffer = '';
249 23
        $arrayPointer = [];
250 23
        $renderedChunkTexts = [];
251 23
        for ($i = 0, ($max = $this->calculateRowHeight($row)) ?: $max = 1; $i < $max; $i++) {
252 23
            $buffer .= $spanLeft . ' ';
253 23
            foreach ($size as $index => $cellSize) {
254 23
                $cell = isset($row[$index]) ? $row[$index] : null;
255 23
                $prefix = '';
256 23
                if ($index !== 0) {
257 21
                    $buffer .= $spanMiddle . ' ';
258
                }
259 23
                if (is_array($cell)) {
260 9
                    if (empty($renderedChunkTexts[$index])) {
261 9
                        $renderedChunkTexts[$index] = '';
262 9
                        $start = 0;
263 9
                        $prefix = $this->listPrefix;
0 ignored issues
show
introduced by
The property listPrefix is declared write-only in yii\console\widgets\Table.
Loading history...
264 9
                        if (!isset($arrayPointer[$index])) {
265 9
                            $arrayPointer[$index] = 0;
266
                        }
267
                    } else {
268 3
                        $start = mb_strwidth($renderedChunkTexts[$index], Yii::$app->charset);
269
                    }
270 9
                    $chunk = Console::ansiColorizedSubstr($cell[$arrayPointer[$index]], $start, $cellSize - 4);
271 9
                    $renderedChunkTexts[$index] .= Console::stripAnsiFormat($chunk);
272 9
                    $fullChunkText = Console::stripAnsiFormat($cell[$arrayPointer[$index]]);
273 9
                    if (isset($cell[$arrayPointer[$index] + 1]) && $renderedChunkTexts[$index] === $fullChunkText) {
274 8
                        $arrayPointer[$index]++;
275 9
                        $renderedChunkTexts[$index] = '';
276
                    }
277
                } else {
278 23
                    $chunk = Console::ansiColorizedSubstr($cell, ($cellSize * $i) - ($i * 2), $cellSize - 2);
279
                }
280 23
                $chunk = $prefix . $chunk;
281 23
                $repeat = $cellSize - Console::ansiStrwidth($chunk) - 1;
282 23
                $buffer .= $chunk;
283 23
                if ($repeat >= 0) {
284 23
                    $buffer .= str_repeat(' ', $repeat);
285
                }
286
            }
287 23
            $buffer .= "$spanRight\n";
288
        }
289
290 23
        return $buffer;
291
    }
292
293
    /**
294
     * Renders separator.
295
     *
296
     * @param string $spanLeft character for left border
297
     * @param string $spanMid character for middle border
298
     * @param string $spanMidMid character for middle-middle border
299
     * @param string $spanRight character for right border
300
     * @return string the generated separator row
301
     * @see \yii\console\widgets\Table::render()
302
     */
303 23
    protected function renderSeparator($spanLeft, $spanMid, $spanMidMid, $spanRight)
304
    {
305 23
        $separator = $spanLeft;
306 23
        foreach ($this->columnWidths as $index => $rowSize) {
307 23
            if ($index !== 0) {
308 21
                $separator .= $spanMid;
309
            }
310 23
            $separator .= str_repeat($spanMidMid, $rowSize);
311
        }
312 23
        $separator .= $spanRight . "\n";
313 23
        return $separator;
314
    }
315
316
    /**
317
     * Calculate the size of rows to draw anchor of columns in console.
318
     *
319
     * @see \yii\console\widgets\Table::render()
320
     */
321 23
    protected function calculateRowsSize()
322
    {
323 23
        $this->columnWidths = $columns = [];
324 23
        $totalWidth = 0;
325 23
        $screenWidth = $this->getScreenWidth() - self::CONSOLE_SCROLLBAR_OFFSET;
326
327 23
        $headerCount = count($this->headers);
328 23
        if (empty($this->rows)) {
329 1
            $rowColCount = 0;
330
        } else {
331 22
            $rowColCount = max(array_map('count', $this->rows));
332
        }
333 23
        $count = max($headerCount, $rowColCount);
334 23
        for ($i = 0; $i < $count; $i++) {
335 23
            $columns[] = ArrayHelper::getColumn($this->rows, $i);
336 23
            if ($i < $headerCount) {
337 22
                $columns[$i][] = $this->headers[$i];
338
            }
339
        }
340
341 23
        foreach ($columns as $column) {
342
            $columnWidth = max(array_map(function ($val) {
343 23
                if (is_array($val)) {
344 9
                    return max(array_map('yii\helpers\Console::ansiStrwidth', $val)) + Console::ansiStrwidth($this->listPrefix);
0 ignored issues
show
introduced by
The property listPrefix is declared write-only in yii\console\widgets\Table.
Loading history...
345
                }
346 23
                return Console::ansiStrwidth($val);
347 23
            }, $column)) + 2;
348 23
            $this->columnWidths[] = $columnWidth;
349 23
            $totalWidth += $columnWidth;
350
        }
351
352 23
        if ($totalWidth > $screenWidth) {
353 9
            $minWidth = 3;
354 9
            $fixWidths = [];
355 9
            $relativeWidth = $screenWidth / $totalWidth;
356 9
            foreach ($this->columnWidths as $j => $width) {
357 9
                $scaledWidth = (int) ($width * $relativeWidth);
358 9
                if ($scaledWidth < $minWidth) {
359 7
                    $fixWidths[$j] = 3;
360
                }
361
            }
362
363 9
            $totalFixWidth = array_sum($fixWidths);
364 9
            $relativeWidth = ($screenWidth - $totalFixWidth) / ($totalWidth - $totalFixWidth);
365 9
            foreach ($this->columnWidths as $j => $width) {
366 9
                if (!array_key_exists($j, $fixWidths)) {
367 7
                    $this->columnWidths[$j] = (int) ($width * $relativeWidth);
368
                }
369
            }
370
        }
371 23
    }
372
373
    /**
374
     * Calculate the height of a row.
375
     *
376
     * @param array $row
377
     * @return int maximum row per cell
378
     * @see \yii\console\widgets\Table::render()
379
     */
380 23
    protected function calculateRowHeight($row)
381
    {
382
        $rowsPerCell = array_map(function ($size, $columnWidth) {
383 23
            if (is_array($columnWidth)) {
384 9
                $rows = 0;
385 9
                foreach ($columnWidth as $width) {
386 9
                    $rows +=  $size == 2 ? 0 : ceil($width / ($size - 2));
387
                }
388 9
                return $rows;
389
            }
390 23
            return $size == 2 || $columnWidth == 0 ? 0 : ceil($columnWidth / ($size - 2));
391 23
        }, $this->columnWidths, array_map(function ($val) {
392 23
            if (is_array($val)) {
393 9
                return array_map('yii\helpers\Console::ansiStrwidth', $val);
394
            }
395 23
            return Console::ansiStrwidth($val);
396 23
        }, $row));
397 23
        return max($rowsPerCell);
398
    }
399
400
    /**
401
     * Getting screen width.
402
     * If it is not able to determine screen width, default value `123` will be set.
403
     *
404
     * @return int screen width
405
     */
406 23
    protected function getScreenWidth()
407
    {
408 23
        if (!$this->screenWidth) {
0 ignored issues
show
introduced by
The property screenWidth is declared write-only in yii\console\widgets\Table.
Loading history...
409 2
            $size = Console::getScreenSize();
410 2
            $this->screenWidth = isset($size[0])
411 2
                ? $size[0]
412
                : self::DEFAULT_CONSOLE_SCREEN_WIDTH + self::CONSOLE_SCROLLBAR_OFFSET;
413
        }
414 23
        return $this->screenWidth;
415
    }
416
}
417