ArrayBlock::toString()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 19
rs 9.7998
cc 4
nc 6
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Schema\Renderer\PhpFileRenderer\Exporter;
6
7
use Cycle\Schema\Renderer\PhpFileRenderer\Exporter\Rendering\Indentable;
8
9
class ArrayBlock implements ExporterItem, Indentable
10
{
11
    protected array $value;
12
    protected array $replaceKeys;
13
    protected array $replaceValues;
14
    private int $indentLevel = 0;
15
16
    public function __construct(array $value, array $replaceKeys = [], array $replaceValues = [])
17
    {
18
        $this->value = $value;
19
        $this->replaceKeys = $replaceKeys;
20
        $this->replaceValues = $replaceValues;
21
    }
22
23
    final public function setIndentLevel(int $indentLevel = 0): self
24
    {
25
        $this->indentLevel = $indentLevel;
26
        return $this;
27
    }
28
29
    final public function toString(): string
30
    {
31
        $result = [];
32
        foreach ($this->value as $key => $value) {
33
            if ($value instanceof ArrayItem) {
34
                $value->setIndentLevel($this->indentLevel + 1);
35
                $result[] = $value->toString();
36
                continue;
37
            }
38
            $item = $this->wrapItem($key, $value);
39
            $item->setIndentLevel($this->indentLevel + 1);
40
41
            $result[] = $item->toString();
42
        }
43
        $indent = \str_repeat(self::INDENT, $this->indentLevel + 1);
44
        $closedIndent = \str_repeat(self::INDENT, $this->indentLevel);
45
        return $result === []
46
            ? '[]'
47
            : "[\n$indent" . \implode(",\n$indent", $result) . ",\n$closedIndent]";
48
    }
49
50
    /**
51
     * @param int|string $key
52
     * @param mixed $value
53
     */
54
    protected function wrapItem($key, $value): ArrayItem
55
    {
56
        $item = isset($this->replaceKeys[$key])
57
            ? new ArrayItem($value, (string)$this->replaceKeys[$key], false)
58
            : new ArrayItem($value, (string)$key, true);
59
60
        if (is_scalar($value) && isset($this->replaceValues[$key][$value])) {
61
            $item->setValue($this->replaceValues[$key][$value], false);
62
        }
63
        return $item;
64
    }
65
}
66