Passed
Pull Request — master (#67)
by Aleksei
15:12
created

ArrayItemRenderer::__toString()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 3
nc 3
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Schema\Converter\SchemaToPHP;
6
7
final class ArrayItemRenderer
8
{
9
    public ?string $key;
10
    /** @var mixed */
11
    public $value;
12
    public bool $wrapValue = true;
13
    public bool $wrapKey;
14
15
    /**
16
     * @param null|string $key
17
     * @param mixed $value
18
     * @param bool $wrapKey
19
     */
20
    public function __construct(?string $key, $value = null, bool $wrapKey = false)
21
    {
22
        $this->key = $key;
23
        $this->value = $value;
24
        $this->wrapKey = $wrapKey;
25
    }
26
27
    public function __toString()
28
    {
29
        $result = '';
30
        if ($this->key !== null) {
31
            $result = $this->wrapKey ? "'{$this->key}' => " : "{$this->key} => ";
32
        }
33
        return $result . $this->renderValue($this->value);
34
    }
35
36
    /**
37
     * @param mixed $value
38
     * @return string
39
     */
40
    private function renderValue($value): string
41
    {
42
        switch (true) {
43
            case $value === null:
44
                return 'null';
45
            case is_bool($value):
46
                return $value ? 'true' : 'false';
47
            case is_array($value):
48
                return $this->renderArray($value);
49
            case !$this->wrapValue || is_int($value) || $value instanceof ArrayItemRenderer:
50
                return (string)$value;
51
            case is_string($value):
52
                return "'" . addslashes($value) . "'";
53
            default:
54
                return "unserialize('" . addslashes(serialize($value)) . "')";
55
        }
56
    }
57
58
    private function renderArray(array $value): string
59
    {
60
        if (count($value) === 0) {
61
            return '[]';
62
        }
63
        $result = '[';
64
        foreach ($value as $key => $item) {
65
            $result .= "\n";
66
            if (!$item instanceof ArrayItemRenderer) {
67
                $result .= is_int($key) ? "{$key} => " : "'{$key}' => ";
68
            }
69
            $result .= $this->renderValue($item) . ',';
70
        }
71
        return str_replace("\n", "\n    ", $result) . "\n]";
72
    }
73
}
74