ScaffoldController.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. namespace Dcat\Admin\Http\Controllers;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Auth\Permission;
  5. use Dcat\Admin\Layout\Content;
  6. use Dcat\Admin\Scaffold\ControllerCreator;
  7. use Dcat\Admin\Scaffold\LangCreator;
  8. use Dcat\Admin\Scaffold\MigrationCreator;
  9. use Dcat\Admin\Scaffold\ModelCreator;
  10. use Dcat\Admin\Scaffold\RepositoryCreator;
  11. use Dcat\Admin\Support\Helper;
  12. use Illuminate\Http\Request;
  13. use Illuminate\Routing\Controller;
  14. use Illuminate\Support\Arr;
  15. use Illuminate\Support\Facades\Artisan;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\URL;
  18. use Illuminate\Support\MessageBag;
  19. use Illuminate\Support\Str;
  20. class ScaffoldController extends Controller
  21. {
  22. public static $dbTypes = [
  23. 'string', 'integer', 'text', 'float', 'double', 'decimal', 'boolean', 'date', 'time',
  24. 'dateTime', 'timestamp', 'char', 'mediumText', 'longText', 'tinyInteger', 'smallInteger',
  25. 'mediumInteger', 'bigInteger', 'unsignedTinyInteger', 'unsignedSmallInteger', 'unsignedMediumInteger',
  26. 'unsignedInteger', 'unsignedBigInteger', 'enum', 'json', 'jsonb', 'dateTimeTz', 'timeTz',
  27. 'timestampTz', 'nullableTimestamps', 'binary', 'ipAddress', 'macAddress',
  28. ];
  29. public static $dataTypeMap = [
  30. 'int' => 'integer',
  31. 'int@unsigned' => 'unsignedInteger',
  32. 'tinyint' => 'tinyInteger',
  33. 'tinyint@unsigned' => 'unsignedTinyInteger',
  34. 'smallint' => 'smallInteger',
  35. 'smallint@unsigned' => 'unsignedSmallInteger',
  36. 'mediumint' => 'mediumInteger',
  37. 'mediumint@unsigned' => 'unsignedMediumInteger',
  38. 'bigint' => 'bigInteger',
  39. 'bigint@unsigned' => 'unsignedBigInteger',
  40. 'date' => 'date',
  41. 'time' => 'time',
  42. 'datetime' => 'dateTime',
  43. 'timestamp' => 'timestamp',
  44. 'enum' => 'enum',
  45. 'json' => 'json',
  46. 'binary' => 'binary',
  47. 'float' => 'float',
  48. 'double' => 'double',
  49. 'decimal' => 'decimal',
  50. 'varchar' => 'string',
  51. 'char' => 'char',
  52. 'text' => 'text',
  53. 'mediumtext' => 'mediumText',
  54. 'longtext' => 'longText',
  55. ];
  56. public function index(Content $content)
  57. {
  58. if (! config('app.debug')) {
  59. Permission::error();
  60. }
  61. if ($tableName = request('singular')) {
  62. return $this->singular($tableName);
  63. }
  64. Admin::requireAssets('select2');
  65. $dbTypes = static::$dbTypes;
  66. $dataTypeMap = static::$dataTypeMap;
  67. $action = URL::current();
  68. $tables = collect($this->getDatabaseColumns())->map(function ($v) {
  69. return array_keys($v);
  70. })->toArray();
  71. return $content
  72. ->title(trans('admin.scaffold.header'))
  73. ->description(' ')
  74. ->body(view(
  75. 'admin::helpers.scaffold',
  76. compact('dbTypes', 'action', 'tables', 'dataTypeMap')
  77. ));
  78. }
  79. protected function singular($tableName)
  80. {
  81. return [
  82. 'status' => 1,
  83. 'value' => Str::singular($tableName),
  84. ];
  85. }
  86. public function store(Request $request)
  87. {
  88. if (! config('app.debug')) {
  89. Permission::error();
  90. }
  91. $paths = [];
  92. $message = '';
  93. $creates = (array) $request->get('create');
  94. $table = Helper::slug($request->get('table_name'), '_');
  95. $controller = $request->get('controller_name');
  96. $model = $request->get('model_name');
  97. $repository = $request->get('repository_name');
  98. try {
  99. // 1. Create model.
  100. if (in_array('model', $creates)) {
  101. $modelCreator = new ModelCreator($table, $model);
  102. $paths['model'] = $modelCreator->create(
  103. $request->get('primary_key'),
  104. $request->get('timestamps') == 1,
  105. $request->get('soft_deletes') == 1
  106. );
  107. }
  108. // 2. Create controller.
  109. if (in_array('controller', $creates)) {
  110. $paths['controller'] = (new ControllerCreator($controller))
  111. ->create(in_array('repository', $creates) ? $repository : $model);
  112. }
  113. // 3. Create migration.
  114. if (in_array('migration', $creates)) {
  115. $migrationName = 'create_'.$table.'_table';
  116. $paths['migration'] = (new MigrationCreator(app('files')))->buildBluePrint(
  117. $request->get('fields'),
  118. $request->get('primary_key', 'id'),
  119. $request->get('timestamps') == 1,
  120. $request->get('soft_deletes') == 1
  121. )->create($migrationName, database_path('migrations'), $table);
  122. }
  123. if (in_array('lang', $creates)) {
  124. $paths['lang'] = (new LangCreator($request->get('fields')))
  125. ->create($controller);
  126. }
  127. if (in_array('repository', $creates)) {
  128. $paths['repository'] = (new RepositoryCreator())
  129. ->create($model, $repository);
  130. }
  131. // Run migrate.
  132. if (in_array('migrate', $creates)) {
  133. Artisan::call('migrate');
  134. $message = Artisan::output();
  135. }
  136. // Make ide helper file.
  137. if (in_array('migrate', $creates) || in_array('controller', $creates)) {
  138. try {
  139. Artisan::call('admin:ide-helper', ['-c' => $controller]);
  140. $paths['ide-helper'] = 'dcat_admin_ide_helper.php';
  141. } catch (\Throwable $e) {
  142. }
  143. }
  144. } catch (\Exception $exception) {
  145. // Delete generated files if exception thrown.
  146. app('files')->delete($paths);
  147. return $this->backWithException($exception);
  148. }
  149. return $this->backWithSuccess($paths, $message);
  150. }
  151. /**
  152. * @return array
  153. */
  154. public function table()
  155. {
  156. $db = addslashes(\request('db'));
  157. $table = \request('tb');
  158. if (! $table || ! $db) {
  159. return ['status' => 1, 'list' => []];
  160. }
  161. $tables = collect($this->getDatabaseColumns($db, $table))
  162. ->filter(function ($v, $k) use ($db) {
  163. return $k == $db;
  164. })->map(function ($v) use ($table) {
  165. return Arr::get($v, $table);
  166. })
  167. ->filter()
  168. ->first();
  169. return ['status' => 1, 'list' => $tables];
  170. }
  171. /**
  172. * @return array
  173. */
  174. protected function getDatabaseColumns($db = null, $tb = null)
  175. {
  176. $databases = Arr::where(config('database.connections', []), function ($value) {
  177. $supports = ['mysql'];
  178. return in_array(strtolower(Arr::get($value, 'driver')), $supports);
  179. });
  180. $data = [];
  181. try {
  182. foreach ($databases as $connectName => $value) {
  183. if ($db && $db != $value['database']) {
  184. continue;
  185. }
  186. $sql = sprintf('SELECT * FROM information_schema.columns WHERE table_schema = "%s"', $value['database']);
  187. if ($tb) {
  188. $p = Arr::get($value, 'prefix');
  189. $sql .= " AND TABLE_NAME = '{$p}{$tb}'";
  190. }
  191. $tmp = DB::connection($connectName)->select($sql);
  192. $collection = collect($tmp)->map(function ($v) use ($value) {
  193. if (! $p = Arr::get($value, 'prefix')) {
  194. return (array) $v;
  195. }
  196. $v = (array) $v;
  197. $v['TABLE_NAME'] = Str::replaceFirst($p, '', $v['TABLE_NAME']);
  198. return $v;
  199. });
  200. $data[$value['database']] = $collection->groupBy('TABLE_NAME')->map(function ($v) {
  201. return collect($v)->keyBy('COLUMN_NAME')->map(function ($v) {
  202. $v['COLUMN_TYPE'] = strtolower($v['COLUMN_TYPE']);
  203. $v['DATA_TYPE'] = strtolower($v['DATA_TYPE']);
  204. if (Str::contains($v['COLUMN_TYPE'], 'unsigned')) {
  205. $v['DATA_TYPE'] .= '@unsigned';
  206. }
  207. return [
  208. 'type' => $v['DATA_TYPE'],
  209. 'default' => $v['COLUMN_DEFAULT'],
  210. 'nullable' => $v['IS_NULLABLE'],
  211. 'key' => $v['COLUMN_KEY'],
  212. 'id' => $v['COLUMN_KEY'] === 'PRI',
  213. 'comment' => $v['COLUMN_COMMENT'],
  214. ];
  215. })->toArray();
  216. })->toArray();
  217. }
  218. } catch (\Throwable $e) {
  219. }
  220. return $data;
  221. }
  222. protected function backWithException(\Exception $exception)
  223. {
  224. $error = new MessageBag([
  225. 'title' => 'Error',
  226. 'message' => $exception->getMessage(),
  227. ]);
  228. return redirect()->refresh()->withInput()->with(compact('error'));
  229. }
  230. protected function backWithSuccess($paths, $message)
  231. {
  232. $messages = [];
  233. foreach ($paths as $name => $path) {
  234. $messages[] = ucfirst($name).": $path";
  235. }
  236. $messages[] = "<br />$message";
  237. $success = new MessageBag([
  238. 'title' => 'Success',
  239. 'message' => implode('<br />', $messages),
  240. ]);
  241. return redirect()->refresh()->with(compact('success'));
  242. }
  243. }