Schema.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CatchAdmin [Just Like ~ ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://catchadmin.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( https://github.com/JaguarJack/catchadmin-laravel/blob/master/LICENSE.md )
  8. // +----------------------------------------------------------------------
  9. // | Author: JaguarJack [ njphper@gmail.com ]
  10. // +----------------------------------------------------------------------
  11. declare(strict_types=1);
  12. namespace Modules\Develop\Support\Generate\Create;
  13. use Catch\CatchAdmin;
  14. use Exception;
  15. use Illuminate\Database\Schema\Blueprint;
  16. use Illuminate\Support\Facades\File;
  17. use Illuminate\Support\Facades\Schema as MigrationSchema;
  18. use Illuminate\Support\Str;
  19. /**
  20. * schema
  21. */
  22. class Schema extends Creator
  23. {
  24. /**
  25. * @var bool
  26. */
  27. protected bool $createdAt = true;
  28. /**
  29. * @var bool
  30. */
  31. protected bool $updatedAt = true;
  32. /**
  33. * @var bool
  34. */
  35. protected bool $deletedAt = true;
  36. /**
  37. * @var bool
  38. */
  39. protected bool $creatorId = true;
  40. /**
  41. * @var array
  42. */
  43. protected array $structures = [];
  44. /**
  45. * @param string $table
  46. * @param string $engine
  47. * @param string $charset
  48. * @param string $collection
  49. * @param string $comment
  50. */
  51. public function __construct(
  52. public readonly string $table,
  53. public readonly string $engine,
  54. public readonly string $charset,
  55. public readonly string $collection,
  56. public readonly string $comment
  57. ) {
  58. }
  59. /**
  60. * create
  61. *
  62. * @return string|bool
  63. * @throws Exception
  64. */
  65. public function create(): string|bool
  66. {
  67. if (! count($this->structures)) {
  68. return false;
  69. }
  70. if (MigrationSchema::hasTable($this->table)) {
  71. throw new Exception(sprintf('[%s] 表已经存在', $this->table));
  72. }
  73. try {
  74. $this->createTable();
  75. if (MigrationSchema::hasTable($this->table)) {
  76. return parent::create();
  77. }
  78. return false;
  79. } catch (Exception $e) {
  80. MigrationSchema::dropIfExists($this->table);
  81. throw new Exception("由于{$e->getMessage()}, 表[{$this->table}]创建失败");
  82. }
  83. }
  84. /**
  85. * get file
  86. *
  87. * @return string
  88. */
  89. public function getFile(): string
  90. {
  91. // TODO: Implement getFile() method.
  92. return CatchAdmin::getModuleMigrationPath($this->module).date('Y_m_d_his_').'create_'.$this->table.'.php';
  93. }
  94. /**
  95. * create table
  96. *
  97. * @throws Exception
  98. */
  99. protected function createTable(): void
  100. {
  101. MigrationSchema::create($this->table, function (Blueprint $table) {
  102. foreach ($this->structures as $structure) {
  103. // if field && type hava value
  104. if ($structure['type'] && $structure['field']) {
  105. if ($structure['type'] == 'string') {
  106. $column = $table->string($structure['field'], $structure['length'] ?: 255);
  107. } elseif ($structure['type'] == 'char') {
  108. $column = $table->char($structure['field'], $structure['length']);
  109. } else {
  110. $column = $table->{$structure['type']}($structure['field']);
  111. }
  112. $column = $column->nullable($structure['nullable']);
  113. if (is_null($structure['default'])) {
  114. } else {
  115. if (is_numeric($structure['default']) || mb_strlen($structure['default'])) {
  116. $column = $column->default($structure['default']);
  117. }
  118. }
  119. if ($structure['comment']) {
  120. $column = $column->comment($structure['comment']);
  121. }
  122. if ($structure['unique']) {
  123. $column->unique($structure['unique']);
  124. }
  125. }
  126. }
  127. if ($this->creatorId) {
  128. $table->creatorId();
  129. }
  130. if ($this->createdAt) {
  131. $table->createdAt();
  132. }
  133. if ($this->updatedAt) {
  134. $table->updatedAt();
  135. }
  136. if ($this->deletedAt) {
  137. $table->deletedAt();
  138. }
  139. $table->charset = $this->charset;
  140. $table->engine = $this->engine;
  141. $table->collation = $this->collection;
  142. $table->comment($this->comment);
  143. });
  144. }
  145. /**
  146. * get migration content
  147. *
  148. * @return string
  149. */
  150. public function getContent(): string
  151. {
  152. $stub = File::get($this->getStub());
  153. return Str::of($stub)->replace(['{method}','{table}', '{content}'], ['create', $this->table, $this->getMigrationContent()])->toString();
  154. }
  155. /**
  156. * get content
  157. *
  158. * @return string
  159. */
  160. public function getMigrationContent(): string
  161. {
  162. $content = Str::of('');
  163. foreach ($this->structures as $structure) {
  164. $begin = Str::of('$table->');
  165. $type = Str::of($structure['type']);
  166. if ($type->exactly('string')) {
  167. $begin = $begin->append(sprintf("string('%s'%s)", $structure['field'], $structure['length'] ? ", {$structure['length']}" : ''));
  168. } elseif ($type->exactly('char')) {
  169. $begin = $begin->append(sprintf("char('%s', %s)", $structure['field'], $structure['length']));
  170. } elseif ($type->exactly('id')) {
  171. $begin = $begin->append(Str::of($structure['field'])->exactly('id') ? 'id()' : sprintf("id('%s')", $structure['field']));
  172. } else {
  173. $begin = $begin->append(sprintf("%s('%s')", $structure['type'], $structure['field']));
  174. }
  175. $content = $content->append($begin)
  176. ->when($structure['nullable'], function ($str) {
  177. return $str->append('->nullable()');
  178. })
  179. ->when(isset($structure['default']), function ($str) use ($structure){
  180. $default = $structure['default'];
  181. if (is_numeric($default)) {
  182. $default = intval($default);
  183. return $str->append("->default({$default})");
  184. }
  185. if ($default) {
  186. return $str->append("->default('{$default}')");
  187. }
  188. return $str;
  189. })
  190. ->when($structure['unique'], function ($str) {
  191. return $str->append("->unique()");
  192. })
  193. ->when($structure['comment'], function ($str, $comment) {
  194. return $str->append("->comment('{$comment}')");
  195. })
  196. ->append(';')
  197. ->newLine();
  198. }
  199. if ($this->creatorId) {
  200. $content = $content->append(Str::of('$table->')->append('creatorId();'))->newLine();
  201. }
  202. if ($this->createdAt) {
  203. $content = $content->append(Str::of('$table->')->append('createdAt();'))->newLine();
  204. }
  205. if ($this->updatedAt) {
  206. $content = $content->append(Str::of('$table->')->append('updatedAt();'))->newLine();
  207. }
  208. if ($this->deletedAt) {
  209. $content = $content->append(Str::of('$table->')->append('deletedAt();'))->newLine();
  210. }
  211. return $content->newLine()
  212. ->append("\$table->engine='{$this->engine}'")
  213. ->append(';')
  214. ->newLine()
  215. ->append("\$table->comment('{$this->comment}')")
  216. ->append(';')
  217. ->toString();
  218. }
  219. /**
  220. * @param bool $createdAt
  221. * @return $this
  222. */
  223. public function setCreatedAt(bool $createdAt): static
  224. {
  225. $this->createdAt = $createdAt;
  226. return $this;
  227. }
  228. /**
  229. * @param bool $updatedAt
  230. * @return $this
  231. */
  232. public function setUpdatedAt(bool $updatedAt): static
  233. {
  234. $this->updatedAt = $updatedAt;
  235. return $this;
  236. }
  237. /**
  238. * @param bool $deletedAt
  239. * @return $this
  240. */
  241. public function setDeletedAt(bool $deletedAt): static
  242. {
  243. $this->deletedAt = $deletedAt;
  244. return $this;
  245. }
  246. /**
  247. * @param bool $creatorId
  248. * @return $this
  249. */
  250. public function setCreatorId(bool $creatorId): static
  251. {
  252. $this->creatorId = $creatorId;
  253. return $this;
  254. }
  255. /**
  256. * @param array $structures
  257. * @return $this
  258. */
  259. public function setStructures(array $structures): static
  260. {
  261. $this->structures = $structures;
  262. return $this;
  263. }
  264. /**
  265. * get stub
  266. *
  267. * @return string
  268. */
  269. protected function getStub(): string
  270. {
  271. return dirname(__DIR__).DIRECTORY_SEPARATOR.'stubs'.DIRECTORY_SEPARATOR.'migration.stub';
  272. }
  273. }