|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Janisbiz\LightOrm; |
|
4
|
|
|
|
|
5
|
|
|
use Janisbiz\LightOrm\Connection\ConnectionInterface; |
|
6
|
|
|
use Janisbiz\LightOrm\Dms\MySQL\Generator\DmsFactory; |
|
7
|
|
|
use Janisbiz\Heredoc\HeredocTrait; |
|
8
|
|
|
use Janisbiz\LightOrm\Generator\Writer\WriterInterface; |
|
9
|
|
|
|
|
10
|
|
|
class Generator |
|
11
|
|
|
{ |
|
12
|
|
|
use HeredocTrait; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @var DmsFactory |
|
16
|
|
|
*/ |
|
17
|
|
|
protected $dmsFactory; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var WriterInterface[] |
|
21
|
|
|
*/ |
|
22
|
|
|
protected $writers = []; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param DmsFactory $dmsFactory |
|
26
|
|
|
*/ |
|
27
|
|
|
public function __construct(DmsFactory $dmsFactory) |
|
28
|
|
|
{ |
|
29
|
|
|
$this->dmsFactory = $dmsFactory; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* @param WriterInterface $writer |
|
34
|
|
|
* |
|
35
|
|
|
* @return $this |
|
36
|
|
|
*/ |
|
37
|
|
|
public function addWriter(WriterInterface $writer): Generator |
|
38
|
|
|
{ |
|
39
|
|
|
$writerClass = \get_class($writer); |
|
40
|
|
|
|
|
41
|
|
|
if (!\array_key_exists($writerClass, $this->writers)) { |
|
42
|
|
|
$this->writers[$writerClass] = $writer; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
return $this; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @param ConnectionInterface $connection |
|
50
|
|
|
* @param string $databaseName |
|
51
|
|
|
* |
|
52
|
|
|
* @return $this |
|
53
|
|
|
*/ |
|
54
|
|
|
public function generate(ConnectionInterface $connection, string $databaseName): Generator |
|
55
|
|
|
{ |
|
56
|
|
|
$dmsDatabase = $this->dmsFactory->createDmsDatabase($databaseName, $connection); |
|
57
|
|
|
|
|
58
|
|
|
foreach ($this->writers as $writer) { |
|
59
|
|
|
$existingFiles = $writer->read($dmsDatabase); |
|
60
|
|
|
|
|
61
|
|
|
foreach ($dmsDatabase->getDmsTables() as $dmsTable) { |
|
62
|
|
|
$writer->write($dmsDatabase, $dmsTable, $existingFiles); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
$this->removeExistingFiles($existingFiles); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return $this; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @param string[] $existingFiles |
|
73
|
|
|
* |
|
74
|
|
|
* @return $this |
|
75
|
|
|
*/ |
|
76
|
|
|
protected function removeExistingFiles(array &$existingFiles): Generator |
|
77
|
|
|
{ |
|
78
|
|
|
foreach (\array_keys($existingFiles) as $path) { |
|
79
|
|
|
if (!\is_dir($path) && \file_exists($path)) { |
|
80
|
|
|
\unlink($path); |
|
81
|
|
|
unset($existingFiles[$path]); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
return $this; |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|