Passed
Pull Request — master (#298)
by Valentin
04:51
created

SchemaCompiler   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 13
c 3
b 0
f 0
dl 0
loc 44
rs 10
wmc 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A isEmpty() 0 3 1
A toSchema() 0 3 2
A toMemory() 0 5 2
A isWriteableSchema() 0 3 2
A compile() 0 3 1
A __construct() 0 3 1
A fromMemory() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Cycle;
6
7
use Cycle\ORM\Schema;
8
use Cycle\ORM\SchemaInterface;
9
use Cycle\Schema\Compiler;
10
use Cycle\Schema\Registry;
11
use Spiral\Boot\MemoryInterface;
12
13
final class SchemaCompiler
14
{
15
    private const MEMORY_SECTION = 'cycle';
16
    private const EMPTY_SCHEMA   = ':empty:';
17
18
    /** @var mixed */
19
    private $schema;
20
21
    private function __construct($schema)
22
    {
23
        $this->schema = $schema;
24
    }
25
26
    public static function fromMemory(MemoryInterface $memory): self
27
    {
28
        return new self($memory->loadData(self::MEMORY_SECTION));
29
    }
30
31
    public static function compile(Registry $registry, array $generators): self
32
    {
33
        return new self((new Compiler())->compile($registry, $generators));
34
    }
35
36
    public function isEmpty(): bool
37
    {
38
        return empty($this->schema);
39
    }
40
41
    public function toSchema(): SchemaInterface
42
    {
43
        return new Schema($this->isWriteableSchema() ? $this->schema : []);
44
    }
45
46
    public function toMemory(MemoryInterface $memory)
47
    {
48
        return $memory->saveData(
49
            self::MEMORY_SECTION,
50
            empty($this->schema) ? self::EMPTY_SCHEMA : $this->schema
51
        );
52
    }
53
54
    private function isWriteableSchema(): bool
55
    {
56
        return is_array($this->schema) && $this->schema !== self::EMPTY_SCHEMA;
57
    }
58
}
59