Passed
Push — master ( 4e0c2f...af0465 )
by Prateek
04:42 queued 02:26
created

Migration   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 26
dl 0
loc 48
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getSchema() 0 17 3
A generate() 0 25 3
1
<?php
2
namespace Prateekkarki\Laragen\Generators\Common;
3
4
use Prateekkarki\Laragen\Generators\BaseGenerator;
5
use Prateekkarki\Laragen\Generators\GeneratorInterface;
6
use Prateekkarki\Laragen\Models\DataOption;
7
8
class Migration extends BaseGenerator implements GeneratorInterface
9
{
10
    protected static $counter = 0;
11
12
    public function generate()
13
    {
14
        $migrationTemplate = $this->buildTemplate('Migration', [
15
            '{{modelName}}'         => $this->module->getModelName(),
16
            '{{modelNamePlural}}'   => $this->module->getModelNamePlural(),
17
            '{{moduleName}}'        => $this->module->getModuleName(),
18
            '{{modelTableSchema}}'  => $this->getSchema()
19
        ]);
20
        
21
        $fileCounter = (int) date('His') + ++self::$counter;
22
        $filenamePrefix = date('Y_m_d_').$fileCounter."_";
23
        $fileName = "create_".$this->module->getModuleName()."_table.php";
24
25
        $existingFiles = scandir($this->getPath("database/migrations/"));
26
        
27
        foreach ($existingFiles as $file) {
28
            if (strpos($file, $fileName) !== false) {
29
                $filenamePrefix = str_replace($fileName, "", $file);
30
            }
31
        }
32
33
        $fullFilePath = $this->getPath("database/migrations/").$filenamePrefix.$fileName;
34
        file_put_contents($fullFilePath, $migrationTemplate);
35
36
        return $fullFilePath;
37
    }
38
39
    protected function getSchema()
40
    {
41
        $schema = "";
42
        $keyArray = array_keys($this->module->getData());
43
        $lastColumn = array_pop($keyArray);
44
45
        foreach ($this->module->getData() as $column => $optionString) {
46
            $option = new DataOption($column, $optionString);
47
48
            $schema .= $option->getSchema();
49
50
            if ($column != $lastColumn) {
51
                $schema .= PHP_EOL.$this->getTabs(3);
52
            }
53
        }
54
55
        return $schema;
56
    }
57
}
58