Completed
Push — master ( b72763...5f55d2 )
by Alec
02:54 queued 11s
created

ColumnizeArray::updateResult()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 1
nop 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
crap 2
1
<?php declare(strict_types=1);
2
3
namespace AlecRabbit\Helpers\Classes;
4
5
use const AlecRabbit\Helpers\Constants\EMPTY_ELEMENTS;
6
7
/**
8
 * Class ColumnizeArray
9
 *
10
 * @internal
11
 */
12
class ColumnizeArray
13
{
14
    /**
15
     * @param array $arr
16
     * @param int $columns
17
     * @param callable|null $preprocessor
18
     * @param int $pad
19
     * @return array
20
     */
21 22
    public static function process(
22
        array $arr,
23
        int $columns = 10,
24
        ?callable $preprocessor = null,
25
        int $pad = STR_PAD_RIGHT
26
    ): array {
27 22
        $result = $tmp = [];
28 22
        $maxLength = static::getMaxLength($arr, $preprocessor);
29 21
        $rowEmpty = true;
30 21
        foreach ($arr as $element) {
31 20
            $tmp[] = \str_pad((string)$element, $maxLength, ' ', $pad);
32 20
            $rowEmpty = $rowEmpty && \in_array($element, EMPTY_ELEMENTS, true);
33 20
            if (\count($tmp) >= $columns) {
34 14
                [$result, $rowEmpty, $tmp] = static::updateResult($result, $rowEmpty, $tmp);
35
            }
36
        }
37 21
        if (!empty($tmp)) {
38 12
            [$result, $rowEmpty, $tmp] = static::updateResult($result, $rowEmpty, $tmp);
39
        }
40 21
        return $result;
41
    }
42
43
44
    /**
45
     * @param array $data
46
     * @param callable|null $preprocessor
47
     * @return int
48
     */
49 33
    protected static function getMaxLength(array &$data, ?callable $preprocessor): int
50
    {
51 33
        $maxLength = 0;
52 33
        foreach ($data as $key => &$element) {
53 32
            if (\is_array($element)) {
54 1
                throw new \RuntimeException('Passed array is multidimensional.');
55
            }
56 31
            if ($preprocessor instanceof \Closure) {
57 3
                $preprocessor($element, $key);
58
            }
59 31
            $len = \strlen($element = (string)$element);
60 31
            if ($maxLength < $len) {
61 23
                $maxLength = $len;
62
            }
63
        }
64 32
        return $maxLength;
65
    }
66
67
    /**
68
     * @param array $result
69
     * @param bool $rowEmpty
70
     * @param array $tmp
71
     * @return array
72
     */
73 24
    protected static function updateResult(array $result, bool $rowEmpty, array $tmp): array
74
    {
75 24
        $result[] = \implode($rowEmpty ? '' : ' ', $tmp);
76 24
        $rowEmpty = true;
77 24
        $tmp = [];
78 24
        return [$result, $rowEmpty, $tmp];
79
    }
80
}
81