|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Yiisoft\Yii\Cycle\Factory; |
|
4
|
|
|
|
|
5
|
|
|
use Closure; |
|
6
|
|
|
use Cycle\ORM\Schema; |
|
7
|
|
|
use Cycle\Schema\Compiler; |
|
8
|
|
|
use Cycle\Schema\GeneratorInterface; |
|
9
|
|
|
use Cycle\Schema\Registry; |
|
10
|
|
|
use Psr\Container\ContainerInterface; |
|
11
|
|
|
use Psr\SimpleCache\CacheInterface; |
|
12
|
|
|
use Spiral\Database\DatabaseManager; |
|
13
|
|
|
use Yiisoft\Yii\Cycle\Conveyor\SchemaConveyorInterface; |
|
14
|
|
|
|
|
15
|
|
|
final class SchemaFromConveyorFactory |
|
16
|
|
|
{ |
|
17
|
|
|
public string $cacheKey; |
|
18
|
|
|
public bool $cacheEnabled; |
|
19
|
|
|
/** @var GeneratorInterface[]|string[]|Closure[] */ |
|
20
|
|
|
private array $generators; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct( |
|
23
|
|
|
bool $cacheEnabled = true, |
|
24
|
|
|
string $cacheKey = 'Cycle-ORM-Schema', |
|
25
|
|
|
array $generators = [] |
|
26
|
|
|
) { |
|
27
|
|
|
$this->cacheEnabled = $cacheEnabled; |
|
28
|
|
|
$this->cacheKey = $cacheKey; |
|
29
|
|
|
$this->generators = $generators; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* @param ContainerInterface $container |
|
34
|
|
|
* @return Schema |
|
35
|
|
|
* @throws \Psr\SimpleCache\InvalidArgumentException |
|
36
|
|
|
* @throws \Yiisoft\Yii\Cycle\Exception\BadGeneratorDeclarationException |
|
37
|
|
|
*/ |
|
38
|
|
|
public function __invoke(ContainerInterface $container) |
|
39
|
|
|
{ |
|
40
|
|
|
$schemaArray = null; |
|
41
|
|
|
if ($this->cacheEnabled) { |
|
42
|
|
|
$schemaArray = $container->get(CacheInterface::class)->get($this->cacheKey); |
|
43
|
|
|
} |
|
44
|
|
|
if (!is_array($schemaArray)) { |
|
45
|
|
|
$schemaArray = $this->generateSchemaArray( |
|
46
|
|
|
$container->get(SchemaConveyorInterface::class), |
|
47
|
|
|
$container->get(DatabaseManager::class) |
|
48
|
|
|
); |
|
49
|
|
|
} |
|
50
|
|
|
if ($this->cacheEnabled) { |
|
51
|
|
|
$container->get(CacheInterface::class)->set($this->cacheKey, $schemaArray); |
|
52
|
|
|
} |
|
53
|
|
|
return new Schema($schemaArray); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @param SchemaConveyorInterface $conveyor |
|
58
|
|
|
* @param DatabaseManager $dbal |
|
59
|
|
|
* @return array |
|
60
|
|
|
* @throws \Yiisoft\Yii\Cycle\Exception\BadGeneratorDeclarationException |
|
61
|
|
|
*/ |
|
62
|
|
|
private function generateSchemaArray(SchemaConveyorInterface $conveyor, DatabaseManager $dbal): array |
|
63
|
|
|
{ |
|
64
|
|
|
// add generators to userland stage |
|
65
|
|
|
foreach ($this->generators as $generator) { |
|
66
|
|
|
$conveyor->addGenerator(SchemaConveyorInterface::STAGE_USERLAND, $generator); |
|
67
|
|
|
} |
|
68
|
|
|
// compile schema array |
|
69
|
|
|
$generators = $conveyor->getGenerators(); |
|
70
|
|
|
return (new Compiler())->compile(new Registry($dbal), $generators); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|