Passed
Push — master ( d8a269...27cede )
by Alexander
02:46 queued 01:01
created

ArrayItem   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 29
c 1
b 0
f 0
dl 0
loc 47
ccs 0
cts 40
cp 0
rs 10
wmc 16

3 Methods

Rating   Name   Duplication   Size   Complexity  
C renderValue() 0 26 12
A __construct() 0 5 1
A __toString() 0 7 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Helper;
6
7
final class ArrayItem
8
{
9
    public ?string $key;
10
    /** @var mixed */
11
    public $value;
12
    public bool $wrapValue = true;
13
    public bool $wrapKey;
14
    public function __construct(?string $key, $value = null, bool $wrapKey = false)
15
    {
16
        $this->key = $key;
17
        $this->value = $value;
18
        $this->wrapKey = $wrapKey;
19
    }
20
    public function __toString()
21
    {
22
        $result = '';
23
        if ($this->key !== null) {
24
            $result = $this->wrapKey ? "'{$this->key}' => " : "{$this->key} => ";
25
        }
26
        return $result . $this->renderValue($this->value);
27
    }
28
    private function renderValue($value)
29
    {
30
        if ($value === null) {
31
            return 'null';
32
        }
33
        if (is_bool($value)) {
34
            return $value ? 'true' : 'false';
35
        }
36
        if (is_array($value)) {
37
            if (count($value) === 0) {
38
                return '[]';
39
            }
40
            $result = '[';
41
            foreach ($value as $key => $item) {
42
                $result .= "\n";
43
                if (!$item instanceof ArrayItem) {
44
                    $result .= is_int($key) ? "{$key} => " : "'{$key}' => ";
45
                }
46
                $result .= $this->renderValue($item) . ',';
47
            }
48
            return str_replace("\n", "\n    ", $result) .  "\n]";
49
        }
50
        if (!$this->wrapValue || is_int($value) || $value instanceof ArrayItem) {
51
            return (string)$value;
52
        }
53
        return "'" . addslashes((string)$value) . "'";
54
    }
55
}
56