Passed
Push — master ( d76988...9ef119 )
by Prateek
04:31 queued 02:30
created

BaseGenerator::initializeFiles()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Prateekkarki\Laragen\Generators;
4
use Prateekkarki\Laragen\Models\Module;
5
6
class BaseGenerator
7
{	
8
    protected $module;
9
10
    public function __construct(Module $module)
11
    {
12
        $this->setModule($module);
13
    }
14
15
    public function getModule()
16
    {
17
        return $this->module;
18
    }
19
20
    public function setModule(Module $module)
21
    {
22
        $this->module = $module;
23
    }
24
25
    public function getStub($type)
26
    {
27
        return str_replace("\r", '', file_get_contents(__DIR__."/../resources/stubs/".$type.".stub"));
28
    }
29
30
    public function getPath($path)
31
    {
32
        $dir = base_path($path);
33
34
        if (!is_dir($dir))
35
            mkdir($dir, 0755, true);
36
37
        return $dir;
38
    }
39
40
    public function moduleToModelName($moduleName)
41
    {
42
        return ucfirst(camel_case(str_singular($moduleName)));
43
    }
44
45
    public function initializeFile($fullFilePath, $stub, $initializeWithText = false) {
46
        if(file_exists($fullFilePath)){
47
            unlink($fullFilePath);
48
        }
49
        $seederTemplate = ($initializeWithText===false) ? $this->buildTemplate($stub) : $initializeWithText;
50
        file_put_contents($fullFilePath, $seederTemplate);
51
        return $fullFilePath;
52
    }
53
54
    public function initializeFiles($fileMaps = []) {
55
        foreach ($fileMaps as $file => $stub) {
56
            $this->initializeFile($file, $stub);
57
        }
58
    }
59
60
    public function buildTemplate($stub, $replacements = [])
61
    {
62
        return str_replace(array_keys($replacements), array_values($replacements), $this->getStub($stub));
63
    }
64
65
    public function updateFile($file, $replacements)
66
    {
67
        return str_replace(array_keys($replacements), array_values($replacements), file_get_contents($file));
68
    }
69
70
    public function insertIntoFile($file_path, $insert_marker, $text, $after = true) {
71
        $contents = str_replace("\r",'', file_get_contents($file_path));
72
        $new_contents = ($after) ? str_replace($insert_marker, $insert_marker.$text, $contents) : str_replace($insert_marker, $text.$insert_marker, $contents); 
73
        return file_put_contents($file_path, $new_contents);
74
    }
75
76
77
    public function getTabs($number)
78
    {
79
        $schema = "";
80
        for ($i = 0; $i < $number; $i++) { 
81
            $schema .= "    ";
82
        }
83
        return $schema;
84
    }
85
}
86