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

SchemaCompiler::toMemory()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 2
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
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