Passed
Pull Request — master (#67)
by Aleksei
27:05 queued 12:08
created

ArrayItemRenderer   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 17
eloc 31
c 0
b 0
f 0
dl 0
loc 62
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __toString() 0 7 3
C renderValue() 0 29 13
A __construct() 0 5 1
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
        if ($value === null) {
43
            return 'null';
44
        }
45
        if (is_bool($value)) {
46
            return $value ? 'true' : 'false';
47
        }
48
        if (is_array($value)) {
49
            if (count($value) === 0) {
50
                return '[]';
51
            }
52
            $result = '[';
53
            foreach ($value as $key => $item) {
54
                $result .= "\n";
55
                if (!$item instanceof ArrayItemRenderer) {
56
                    $result .= is_int($key) ? "{$key} => " : "'{$key}' => ";
57
                }
58
                $result .= $this->renderValue($item) . ',';
59
            }
60
            return str_replace("\n", "\n    ", $result) . "\n]";
61
        }
62
        if (!$this->wrapValue || is_int($value) || $value instanceof ArrayItemRenderer) {
63
            return (string)$value;
64
        }
65
        if (is_string($value)) {
66
            return "'" . addslashes($value) . "'";
67
        }
68
        return "unserialize('" . addslashes(serialize($value)) . "')";
69
    }
70
}
71