Completed
Push — array-output ( a2191f )
by Craig
01:47
created

PadArray   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 1
dl 0
loc 80
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 2
C convertValuesToStrings() 0 27 7
A getMaxStringLength() 0 14 3
1
<?php
2
3
namespace League\CLImate\TerminalObject\Dynamic;
4
5
class PadArray extends Padding
6
{
7
8
    /**
9
     * If they pass in a padding character, set the char
10
     *
11
     * @param array $data
12
     * @param string $char The character to use for padding
13
     */
14
    public function __construct(array $data, $char = null)
15
    {
16
        $data = $this->convertValuesToStrings($data);
17
        $length = $this->getMaxStringLength(array_keys($data));
18
19
        parent::__construct($length, $char);
20
21
        foreach ($data as $key => $value) {
22
            $this->label($key)->result($value);
23
        }
24
    }
25
26
27
    /**
28
     * Convert every key/value in the array to a string
29
     *
30
     * @param array $data
31
     *
32
     * @return array
33
     */
34
    protected function convertValuesToStrings(array $data)
35
    {
36
        $strings = [];
37
38
        # Convert each element in the array to a string
39
        foreach ($data as $key => $value) {
40
            $type = strtolower(gettype($value));
41
            switch ($type) {
42
                case 'boolean':
43
                    $value = $value ? '[true]' : '[false]';
44
                    break;
45
                case 'array':
46
                case 'object':
47
                case 'resource':
48
                    $value = '[' . $type . ']';
49
                    break;
50
                default:
51
                    $value = (string) $value;
52
                    break;
53
            }
54
55
            $key = (string) $key;
56
            $strings[$key] = $value;
57
        }
58
59
        return $strings;
60
    }
61
62
63
    /**
64
     * Get the length of the longest string so we know how much padding we need
65
     *
66
     * @param string[] $keys
67
     *
68
     * @return int
69
     */
70
    protected function getMaxStringLength(array $keys)
71
    {
72
        # Default to at least 5 spaces of padding
73
        $max = 5;
74
75
        foreach ($keys as $key) {
76
            $length = strlen($key);
77
            if ($length > $max) {
78
                $max = $length;
79
            }
80
        }
81
82
        return $max;
83
    }
84
}
85