Skip to content

Commit 7c0facc

Browse files
committed
some refactoring for Maintainability
1 parent 07e0a05 commit 7c0facc

File tree

6 files changed

+163
-132
lines changed

6 files changed

+163
-132
lines changed

src/Service/Generator/Compiler/Engine/ReplaceEngine.php

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,20 @@ public function get($path, array $data = []): string
2020

2121
protected function populateData(string $content, array $data): string
2222
{
23+
$result = $content;
2324
foreach ($data as $key => $value) {
24-
if (!is_object($value)) {
25-
if (is_array($value)) {
26-
$string = '';
27-
foreach ($value as $val) {
28-
$string .= $val;
29-
}
30-
31-
$value = $string;
32-
}
33-
$content = str_replace('{{$' . $key . '}}', (string)$value, $content);
25+
if (is_object($value)) {
26+
continue;
3427
}
28+
29+
if (is_array($value)) {
30+
$value = implode('', $value);
31+
}
32+
33+
$result = str_replace('{{$'.$key.'}}', (string) $value, $result);
3534
}
3635

37-
return $content;
36+
return $result;
3837
}
3938

4039
}

src/Service/Generator/Compiler/Mapper/FieldMapper.php

Lines changed: 36 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -22,48 +22,59 @@ public function map(array $data): array
2222

2323
protected function generateField(FieldEntity $fieldEntity): string
2424
{
25-
$argumentString = '';
26-
$arguments = $fieldEntity->getArguments();
27-
$options = $fieldEntity->getOptions();
28-
foreach ($arguments as $argument) {
29-
if (null !== $argument) {
30-
$argumentString .= ', ';
31-
if (is_bool($argument)) {
32-
$argumentString .= $argument ? 'true' : 'false';
33-
} elseif (is_int($argument)) {
34-
$argumentString .= $argument;
35-
} else {
36-
$argumentString .= "'" . $argument . "'";
37-
}
38-
}
39-
}
25+
$argumentString = $this->renderArguments($fieldEntity->getArguments());
4026

4127
$methods = [
4228
$fieldEntity->getType() . "('" . $fieldEntity->getColumnName() . "'" . $argumentString . ")",
29+
...$this->getFluentOptions($fieldEntity->getOptions()),
4330
];
4431

45-
if (array_key_exists('default', $options) && null !== $options['default']) {
46-
if ('CURRENT_TIMESTAMP' === $options['default']) {
47-
$default = "default(DB::raw('CURRENT_TIMESTAMP'))";
32+
return $this->chainMethodsToString($methods);
33+
}
34+
35+
private function renderArguments(array $arguments): string
36+
{
37+
$args = [];
38+
39+
foreach ($arguments as $arg) {
40+
if ($arg === null) {
41+
continue;
42+
}
43+
44+
if (is_bool($arg)) {
45+
$args[] = $arg ? 'true' : 'false';
46+
} elseif (is_int($arg)) {
47+
$args[] = $arg;
4848
} else {
49-
$default = "default('" . $options['default'] . "')";
49+
$args[] = "'" . $arg . "'";
5050
}
51+
}
52+
53+
return count($args) > 0 ? ', ' . implode(', ', $args) : '';
54+
}
5155

52-
$methods[] = $default;
56+
private function getFluentOptions(array $options): array
57+
{
58+
$methods = [];
59+
60+
if (!empty($options['default'])) {
61+
$methods[] = $options['default'] === 'CURRENT_TIMESTAMP'
62+
? "default(DB::raw('CURRENT_TIMESTAMP'))"
63+
: "default('" . $options['default'] . "')";
5364
}
5465

55-
if (array_key_exists('unsigned', $options) && true === $options['unsigned']) {
56-
$methods[] = "unsigned()";
66+
if (!empty($options['unsigned'])) {
67+
$methods[] = 'unsigned()';
5768
}
5869

59-
if (array_key_exists('nullable', $options) && true === $options['nullable']) {
70+
if (!empty($options['nullable'])) {
6071
$methods[] = 'nullable()';
6172
}
6273

63-
if (array_key_exists('comment', $options) && !empty($options['comment'])) {
74+
if (!empty($options['comment'])) {
6475
$methods[] = "comment('" . addcslashes($options['comment'], "\\'") . "')";
6576
}
6677

67-
return $this->chainMethodsToString($methods);
78+
return $methods;
6879
}
6980
}

src/Service/Generator/Compiler/MigrationCompiler.php

Lines changed: 62 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@
44
namespace N3XT0R\MigrationGenerator\Service\Generator\Compiler;
55

66
use Illuminate\Database\Migrations\Migration;
7-
use N3XT0R\MigrationGenerator\Service\Generator\Compiler\Mapper\MapperInterface;
8-
use Illuminate\View\Factory as ViewFactory;
97
use Illuminate\Filesystem\Filesystem;
8+
use Illuminate\Support\Str;
9+
use Illuminate\View\Factory as ViewFactory;
10+
use N3XT0R\MigrationGenerator\Service\Generator\Compiler\Mapper\MapperInterface;
1011
use N3XT0R\MigrationGenerator\Service\Generator\Definition\Entity\ResultEntity;
1112
use N3XT0R\MigrationGenerator\Service\Generator\Sort\TopSort;
12-
use Illuminate\Support\Str;
1313

1414
class MigrationCompiler implements MigrationCompilerInterface
1515
{
@@ -44,7 +44,7 @@ public function getMapper(): array
4444
}
4545

4646
/**
47-
* @param array $mapper
47+
* @param array $mapper
4848
*/
4949
public function setMapper(array $mapper): void
5050
{
@@ -70,7 +70,7 @@ public function getFilesystem(): Filesystem
7070
}
7171

7272
/**
73-
* @param Filesystem $filesystem
73+
* @param Filesystem $filesystem
7474
*/
7575
public function setFilesystem(Filesystem $filesystem): void
7676
{
@@ -86,7 +86,7 @@ public function getMigrationFiles(): array
8686
}
8787

8888
/**
89-
* @param array $migrationFiles
89+
* @param array $migrationFiles
9090
*/
9191
public function setMigrationFiles(array $migrationFiles): void
9292
{
@@ -114,64 +114,88 @@ public function generateByResult(ResultEntity $resultEntity, string $customMigra
114114
$mapper = $this->getMapper();
115115
$sortedMapper = TopSort::sort($mapper);
116116

117-
$data = [
118-
'migrationNamespace' => 'use ' . Migration::class . ';',
119-
'tableName' => $tableName,
120-
'columns' => [],
121-
];
122-
123-
if (!empty($customMigrationClass) && class_exists($customMigrationClass)) {
124-
$data['migrationNamespace'] = 'use ' . $customMigrationClass . ';';
125-
}
117+
$migrationNamespace = $this->resolveMigrationNamespace($customMigrationClass);
118+
$migrationClass = $this->extractClassFromNamespace($migrationNamespace);
126119

127-
$namespaceParts = explode('\\', str_replace(';', '', $data['migrationNamespace']));
128-
$data['migrationClass'] = $namespaceParts[count($namespaceParts) - 1];
120+
$columns = [];
129121

130-
foreach ($sortedMapper as $key => $mappingName) {
122+
foreach ($sortedMapper as $mappingName) {
131123
$mapping = app()->make($mapper[$mappingName]['class']);
132124
if ($mapping instanceof MapperInterface) {
133125
$resultData = $resultEntity->getResultByTableNameAndKey($tableName, $mappingName);
134-
$extractedLines = $mapping->map($resultData);
135-
$data['columns'] = array_merge($data['columns'], $extractedLines);
126+
foreach ($mapping->map($resultData) as $line) {
127+
$columns[] = $line;
128+
}
136129
}
137130
}
138131

132+
$data = [
133+
'migrationNamespace' => $migrationNamespace,
134+
'migrationClass' => $migrationClass,
135+
'tableName' => $tableName,
136+
'columns' => $columns,
137+
];
138+
139139
$this->setRenderedTemplate($this->render('migration-generator::CreateTableStub', $data));
140140
}
141141

142+
private function resolveMigrationNamespace(string $customClass): string
143+
{
144+
return (!empty($customClass) && class_exists($customClass))
145+
? 'use '.$customClass.';'
146+
: 'use '.Migration::class.';';
147+
}
148+
149+
private function extractClassFromNamespace(string $namespaceLine): string
150+
{
151+
$parts = explode('\\', str_replace(';', '', $namespaceLine));
152+
return end($parts);
153+
}
154+
142155
public function writeToDisk(
143156
string $name,
144157
string $path,
145158
int $currentAmount = -1,
146159
int $maxAmount = -1,
147160
int $timestamp = -1
148161
): bool {
149-
$this->setMigrationFiles([]);
150162
$result = false;
163+
$this->setMigrationFiles([]);
151164
$tpl = $this->getRenderedTemplate();
152-
if (!empty($tpl)) {
153-
$filesystem = $this->getFilesystem();
154-
$datePrefix = date('Y_m_d_His');
155-
if (-1 !== $currentAmount && -1 !== $maxAmount && -1 !== $timestamp) {
156-
$datePrefix = $this->getHourMinuteSecondPrefix($currentAmount, $maxAmount, $timestamp);
157-
}
158165

159-
$fileName = $datePrefix . '_' . Str::snake($name) . '.php';
166+
if (!empty($tpl)) {
167+
$fileName = $this->generateFilename($name, $currentAmount, $maxAmount, $timestamp);
160168
$renderedTemplate = str_replace('DummyClass', Str::studly($name), $tpl);
169+
$result = $this->writeTemplateToFile($path, $fileName, $renderedTemplate);
170+
}
161171

162-
if ($filesystem->exists($path)) {
163-
$fileLocation = $path . DIRECTORY_SEPARATOR . $fileName;
164-
if (false === $filesystem->exists($fileLocation)) {
165-
$result = $filesystem->put($fileLocation, $renderedTemplate) > 0;
166-
if (true === $result) {
167-
$this->addMigrationFile($fileName);
168-
}
169-
}
172+
return $result;
173+
}
174+
175+
private function generateFilename(string $name, int $currentAmount, int $maxAmount, int $timestamp): string
176+
{
177+
$prefix = ($currentAmount !== -1 && $maxAmount !== -1 && $timestamp !== -1)
178+
? $this->getHourMinuteSecondPrefix($currentAmount, $maxAmount, $timestamp)
179+
: date('Y_m_d_His');
180+
181+
return $prefix.'_'.Str::snake($name).'.php';
182+
}
183+
184+
private function writeTemplateToFile(string $path, string $fileName, string $content): bool
185+
{
186+
$filesystem = $this->getFilesystem();
187+
$filePath = $path.DIRECTORY_SEPARATOR.$fileName;
188+
$success = false;
189+
190+
if ($filesystem->exists($path) && !$filesystem->exists($filePath)) {
191+
$success = $filesystem->put($filePath, $content) > 0;
192+
193+
if ($success) {
194+
$this->addMigrationFile($fileName);
170195
}
171196
}
172197

173-
174-
return $result;
198+
return $success;
175199
}
176200

177201
private function getHourMinuteSecondPrefix(int $actual, int $max, int $timestamp): string

src/Service/Generator/Definition/ForeignKeyDefinition.php

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66

77
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
8-
use N3XT0R\MigrationGenerator\Service\Generator\Definition\Entity\FieldEntity;
98
use N3XT0R\MigrationGenerator\Service\Generator\Definition\Entity\ForeignKeyEntity;
109

1110
class ForeignKeyDefinition extends AbstractDefinition
@@ -14,7 +13,7 @@ protected function generateData(): array
1413
{
1514
$table = $this->getAttributeByName('tableName');
1615
$schema = $this->getSchema();
17-
$tableResult = (array)$this->getAttributeByName('table');
16+
$tableResult = (array) $this->getAttributeByName('table');
1817
$result = [];
1918
if (0 !== count($tableResult)) {
2019
$result = $this->generateForeignKeys($table, $schema->listTableForeignKeys($table));
@@ -28,27 +27,26 @@ protected function generateForeignKeys(string $table, array $foreignKeys): array
2827
$result = [];
2928

3029
foreach ($foreignKeys as $foreignKey) {
31-
if ($foreignKey instanceof ForeignKeyConstraint) {
32-
$localColumn = $foreignKey->getLocalColumns()[0];
33-
34-
35-
$foreignKeyEntity = new ForeignKeyEntity();
36-
$foreignKeyEntity->setName($foreignKey->getName());
37-
$foreignKeyEntity->setLocalTable($table);
38-
$foreignKeyEntity->setLocalColumn($localColumn);
39-
$foreignKeyEntity->setReferencedTable($foreignKey->getForeignTableName());
40-
$foreignKeyEntity->setReferencedColumn($foreignKey->getForeignColumns()[0]);
30+
if (!($foreignKey instanceof ForeignKeyConstraint)) {
31+
continue;
32+
}
4133

42-
if ($foreignKey->hasOption('onUpdate')) {
43-
$foreignKeyEntity->setOnUpdate($foreignKey->getOption('onUpdate'));
44-
}
34+
$entity = new ForeignKeyEntity();
35+
$entity->setName($foreignKey->getName());
36+
$entity->setLocalTable($table);
37+
$entity->setLocalColumn($foreignKey->getLocalColumns()[0]);
38+
$entity->setReferencedTable($foreignKey->getForeignTableName());
39+
$entity->setReferencedColumn($foreignKey->getForeignColumns()[0]);
4540

46-
if ($foreignKey->hasOption('onDelete')) {
47-
$foreignKeyEntity->setOnDelete($foreignKey->getOption('onDelete'));
48-
}
41+
if ($foreignKey->hasOption('onUpdate')) {
42+
$entity->setOnUpdate($foreignKey->getOption('onUpdate'));
43+
}
4944

50-
$result[] = $foreignKeyEntity;
45+
if ($foreignKey->hasOption('onDelete')) {
46+
$entity->setOnDelete($foreignKey->getOption('onDelete'));
5147
}
48+
49+
$result[] = $entity;
5250
}
5351

5452
return $result;

src/Service/Generator/Definition/IndexDefinition.php

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,14 @@
55

66

77
use Doctrine\DBAL\Schema\Index;
8-
use N3XT0R\MigrationGenerator\Service\Generator\Definition\Entity\FieldEntity;
98
use N3XT0R\MigrationGenerator\Service\Generator\Definition\Entity\IndexEntity;
109

1110
class IndexDefinition extends AbstractDefinition
1211
{
1312
protected function generateData(): array
1413
{
1514
$table = $this->getAttributeByName('tableName');
16-
$tableResult = (array)$this->getAttributeByName('table');
15+
$tableResult = (array) $this->getAttributeByName('table');
1716
$schema = $this->getSchema();
1817

1918
$result = [];
@@ -28,24 +27,19 @@ protected function generateData(): array
2827
protected function generateIndexes(array $indexes): array
2928
{
3029
$combinedIndexes = [];
30+
3131
foreach ($indexes as $index) {
32-
if ($index instanceof Index === false || $index->getName() === 'PRIMARY') {
32+
if (!($index instanceof Index) || $index->getName() === 'PRIMARY') {
3333
continue;
3434
}
3535

36-
$fieldEntity = null;
37-
$columns = $index->getColumns();
38-
39-
if ($index->isUnique()) {
40-
$type = 'unique';
41-
} else {
42-
$type = 'index';
43-
}
36+
$type = $index->isUnique() ? 'unique' : 'index';
4437

4538
$indexEntity = new IndexEntity();
4639
$indexEntity->setType($type);
4740
$indexEntity->setName($index->getName());
48-
$indexEntity->setColumns($columns);
41+
$indexEntity->setColumns($index->getColumns());
42+
4943
$combinedIndexes[$index->getName()] = $indexEntity;
5044
}
5145

0 commit comments

Comments
 (0)