PropertyRenderer::convertArrayToString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 12
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Schema\Renderer\ConsoleRenderer\Renderer;
6
7
use Cycle\Schema\Renderer\ConsoleRenderer\Formatter;
8
use Cycle\Schema\Renderer\ConsoleRenderer\Renderer;
9
10
class PropertyRenderer implements Renderer
11
{
12
    private int $property;
13
    private string $title;
14
    private bool $required;
15
16
    public function __construct(int $property, string $title, bool $required = false)
17
    {
18
        $this->property = $property;
19
        $this->title = $title;
20
        $this->required = $required;
21
    }
22
23
    public function render(Formatter $formatter, array $schema, string $role): ?string
24
    {
25
        $row = \sprintf('%s: ', $formatter->title($this->title));
26
27
        if (! isset($schema[$this->property])) {
28
            return $this->required ? $row . $formatter->error('not defined') : null;
29
        }
30
31
        $propertyValue = $schema[$this->property];
32
33
        if (\is_array($propertyValue)) {
34
            if (\count($propertyValue) >= 1) {
35
                return $row . $this->convertArrayToString($formatter, $propertyValue);
36
            }
37
            $propertyValue = '[]';
38
        }
39
40
        return \sprintf(
41
            '%s%s',
42
            $row,
43
            $formatter->typecast($propertyValue)
44
        );
45
    }
46
47
    private function convertArrayToString(Formatter $formatter, array $values): string
48
    {
49
        $string = \implode(
50
            "\n",
51
            \array_map(static fn ($property) => \sprintf(
52
                '  %s%s',
53
                $formatter->title(' '),
54
                $formatter->typecast($property)
55
            ), $values)
56
        );
57
58
        return \ltrim($string);
59
    }
60
}
61