ScaffoldController.php 9.0 KB

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