PhpSchemaRenderer   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 26
c 1
b 0
f 0
dl 0
loc 53
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A wrapRoleSchema() 0 5 1
A render() 0 22 3
A getSchemaConstants() 0 11 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Schema\Renderer;
6
7
use Cycle\ORM\SchemaInterface;
8
use Cycle\Schema\Renderer\PhpFileRenderer\Exporter\ArrayBlock;
9
use Cycle\Schema\Renderer\PhpFileRenderer\Exporter\ArrayItem;
10
use Cycle\Schema\Renderer\PhpFileRenderer\Exporter\ExporterItem;
11
use Cycle\Schema\Renderer\PhpFileRenderer\Item\RoleBlock;
12
13
/**
14
 * The Renderer generates valid PHP code, in which constants from {@see \Cycle\ORM\Relation} and
15
 * {@see \Cycle\ORM\SchemaInterface} are substituted for better readability.
16
 */
17
class PhpSchemaRenderer implements SchemaRenderer
18
{
19
    private const USE_LIST = [
20
        'Cycle\ORM\Relation',
21
        'Cycle\ORM\SchemaInterface as Schema',
22
    ];
23
24
    final public function render(array $schema): string
25
    {
26
        $result = "<?php\n\ndeclare(strict_types=1);\n\n";
27
28
        // The `use` block
29
        foreach (self::USE_LIST as $use) {
30
            $result .= "use {$use};\n";
31
        }
32
33
        $items = [];
34
        foreach ($schema as $role => $roleSchema) {
35
            $item = new ArrayItem(
36
                $this->wrapRoleSchema($roleSchema),
37
                $role,
38
                true
39
            );
40
            $items[] = $item->setIndentLevel();
41
        }
42
43
        $rendered = (new ArrayBlock($items))->toString();
44
45
        return $result . "\nreturn {$rendered};\n";
46
    }
47
48
    protected function wrapRoleSchema(array $roleSchema): ExporterItem
49
    {
50
        return new RoleBlock(
51
            $roleSchema,
52
            $this->getSchemaConstants()
53
        );
54
    }
55
56
    /**
57
     * @return array<int, string> (Option value => constant name) array
58
     */
59
    final protected function getSchemaConstants(): array
60
    {
61
        $result = array_filter(
62
            (new \ReflectionClass(SchemaInterface::class))->getConstants(),
63
            static fn ($value): bool => is_int($value)
64
        );
65
        $result = array_flip($result);
66
        array_walk($result, static function (string &$name): void {
67
            $name = "Schema::$name";
68
        });
69
        return $result;
70
    }
71
}
72