1 <?php
2
3 namespace Scaffolder\Compilers\Core;
4
5 use Illuminate\Support\Facades\File;
6 use Scaffolder\Compilers\AbstractCoreCompiler;
7 use Scaffolder\Support\FileToCompile;
8 use Scaffolder\Support\PathParser;
9 use stdClass;
10
11 class ControllerCompiler extends AbstractCoreCompiler
12 {
13 14 15 16 17 18 19 20 21 22 23 24 25
26 public function compile($stub, $modelName, $modelData, stdClass $scaffolderConfig, $hash, array $extensions, $extra = null)
27 {
28 if (File::exists(base_path('scaffolder-config/cache/controller_' . $hash . self::CACHE_EXT)))
29 {
30 return $this->store($modelName, $scaffolderConfig, '', new FileToCompile(true, $hash));
31 }
32 else
33 {
34 $this->stub = $stub;
35
36 $this->replaceClassName($modelName)
37 ->setValidations($modelData)
38 ->replacePrimaryKey($modelData)
39 ->replaceRoutePrefix($scaffolderConfig->routing->prefix);
40
41 foreach ($extensions as $extension)
42 {
43 $this->stub = $extension->runAfterControllerIsCompiled($this->stub, $modelData, $scaffolderConfig);
44 }
45
46 return $this->store($modelName, $scaffolderConfig, $this->stub, new FileToCompile(false, $hash));
47 }
48 }
49
50 51 52 53 54 55 56 57 58 59
60 protected function store($modelName, stdClass $scaffolderConfig, $compiled, FileToCompile $fileToCompile)
61 {
62 $path = PathParser::parse($scaffolderConfig->paths->controllers) . $modelName . 'Controller.php';
63
64
65 if ($fileToCompile->cached)
66 {
67 File::copy(base_path('scaffolder-config/cache/controller_' . $fileToCompile->hash . self::CACHE_EXT), $path);
68 }
69 else
70 {
71 File::put(base_path('scaffolder-config/cache/controller_' . $fileToCompile->hash . self::CACHE_EXT), $compiled);
72 File::copy(base_path('scaffolder-config/cache/controller_' . $fileToCompile->hash . self::CACHE_EXT), $path);
73 }
74
75 return $path;
76 }
77
78 79 80 81 82 83 84
85 protected function setValidations($modelData)
86 {
87 $fields = '';
88 $firstIteration = true;
89
90 foreach ($modelData->fields as $field)
91 {
92 if ($firstIteration)
93 {
94 $fields .= sprintf("'%s' => '%s'," . PHP_EOL, $field->name, $field->validations);
95 $firstIteration = false;
96 }
97 else
98 {
99 $fields .= sprintf($this->tab(3) . "'%s' => '%s'," . PHP_EOL, $field->name, $field->validations);
100 }
101 }
102
103 $this->stub = str_replace('{{validations}}', $fields, $this->stub);
104
105 return $this;
106 }
107
108 109 110 111 112 113 114
115 private function replaceRoutePrefix($prefix)
116 {
117 $this->stub = str_replace('{{route_prefix}}', $prefix, $this->stub);
118
119 return $this;
120 }
121
122 123 124 125 126 127 128
129 private function replacePrimaryKey($modelData)
130 {
131 $primaryKey = 'id';
132
133 foreach ($modelData->fields as $field)
134 {
135 if ($field->index == 'primary')
136 {
137 $primaryKey = $field->name;
138 break;
139 }
140 }
141
142 $this->stub = str_replace('{{primaryKey}}', $primaryKey, $this->stub);
143
144 return $this;
145 }
146 }
147