GeneratorCommand.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. <?php
  2. namespace Dcat\Admin\Console;
  3. use Dcat\Admin\Support\Helper;
  4. use Illuminate\Console\Concerns\CreatesMatchingTest;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Filesystem\Filesystem;
  7. use Illuminate\Support\Str;
  8. use Symfony\Component\Console\Input\InputArgument;
  9. abstract class GeneratorCommand extends Command
  10. {
  11. protected $baseDirectory;
  12. /**
  13. * The filesystem instance.
  14. *
  15. * @var \Illuminate\Filesystem\Filesystem
  16. */
  17. protected $files;
  18. /**
  19. * The type of class being generated.
  20. *
  21. * @var string
  22. */
  23. protected $type;
  24. /**
  25. * Reserved names that cannot be used for generation.
  26. *
  27. * @var string[]
  28. */
  29. protected $reservedNames = [
  30. '__halt_compiler',
  31. 'abstract',
  32. 'and',
  33. 'array',
  34. 'as',
  35. 'break',
  36. 'callable',
  37. 'case',
  38. 'catch',
  39. 'class',
  40. 'clone',
  41. 'const',
  42. 'continue',
  43. 'declare',
  44. 'default',
  45. 'die',
  46. 'do',
  47. 'echo',
  48. 'else',
  49. 'elseif',
  50. 'empty',
  51. 'enddeclare',
  52. 'endfor',
  53. 'endforeach',
  54. 'endif',
  55. 'endswitch',
  56. 'endwhile',
  57. 'eval',
  58. 'exit',
  59. 'extends',
  60. 'final',
  61. 'finally',
  62. 'fn',
  63. 'for',
  64. 'foreach',
  65. 'function',
  66. 'global',
  67. 'goto',
  68. 'if',
  69. 'implements',
  70. 'include',
  71. 'include_once',
  72. 'instanceof',
  73. 'insteadof',
  74. 'interface',
  75. 'isset',
  76. 'list',
  77. 'namespace',
  78. 'new',
  79. 'or',
  80. 'print',
  81. 'private',
  82. 'protected',
  83. 'public',
  84. 'require',
  85. 'require_once',
  86. 'return',
  87. 'static',
  88. 'switch',
  89. 'throw',
  90. 'trait',
  91. 'try',
  92. 'unset',
  93. 'use',
  94. 'var',
  95. 'while',
  96. 'xor',
  97. 'yield',
  98. ];
  99. /**
  100. * Create a new controller creator command instance.
  101. *
  102. * @param \Illuminate\Filesystem\Filesystem $files
  103. * @return void
  104. */
  105. public function __construct(Filesystem $files)
  106. {
  107. parent::__construct();
  108. if (in_array(CreatesMatchingTest::class, class_uses_recursive($this))) {
  109. $this->addTestOptions();
  110. }
  111. $this->files = $files;
  112. }
  113. /**
  114. * Get the stub file for the generator.
  115. *
  116. * @return string
  117. */
  118. abstract protected function getStub();
  119. /**
  120. * Execute the console command.
  121. *
  122. * @return bool|null
  123. *
  124. * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
  125. */
  126. public function handle()
  127. {
  128. // First we need to ensure that the given name is not a reserved word within the PHP
  129. // language and that the class name will actually be valid. If it is not valid we
  130. // can error now and prevent from polluting the filesystem using invalid files.
  131. if ($this->isReservedName($this->getNameInput())) {
  132. $this->error('The name "'.$this->getNameInput().'" is reserved by PHP.');
  133. return false;
  134. }
  135. $name = $this->qualifyClass($this->getNameInput());
  136. $path = $this->getPath($name);
  137. // Next, We will check to see if the class already exists. If it does, we don't want
  138. // to create the class and overwrite the user's code. So, we will bail out so the
  139. // code is untouched. Otherwise, we will continue generating this class' files.
  140. if ((! $this->hasOption('force') ||
  141. ! $this->option('force')) &&
  142. $this->alreadyExists($this->getNameInput())) {
  143. $this->error($this->type.' already exists!');
  144. return false;
  145. }
  146. // Next, we will generate the path to the location where this class' file should get
  147. // written. Then, we will build the class and make the proper replacements on the
  148. // stub files so that it gets the correctly formatted namespace and class name.
  149. $this->makeDirectory($path);
  150. $this->files->put($path, $this->sortImports($this->buildClass($name)));
  151. $this->info($this->type.' created successfully.');
  152. if (in_array(CreatesMatchingTest::class, class_uses_recursive($this))) {
  153. $this->handleTestCreation($path);
  154. }
  155. }
  156. /**
  157. * Parse the class name and format according to the root namespace.
  158. *
  159. * @param string $name
  160. * @return string
  161. */
  162. protected function qualifyClass($name)
  163. {
  164. $name = ltrim($name, '\\/');
  165. $name = str_replace('/', '\\', $name);
  166. $rootNamespace = $this->rootNamespace();
  167. if (Str::startsWith($name, $rootNamespace)) {
  168. return $name;
  169. }
  170. return $this->qualifyClass(
  171. $this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name
  172. );
  173. }
  174. /**
  175. * Qualify the given model class base name.
  176. *
  177. * @param string $model
  178. * @return string
  179. */
  180. protected function qualifyModel(string $model)
  181. {
  182. $model = ltrim($model, '\\/');
  183. $model = str_replace('/', '\\', $model);
  184. $rootNamespace = $this->rootNamespace();
  185. if (Str::startsWith($model, $rootNamespace)) {
  186. return $model;
  187. }
  188. return is_dir(app_path('Models'))
  189. ? $rootNamespace.'Models\\'.$model
  190. : $rootNamespace.$model;
  191. }
  192. /**
  193. * Get the default namespace for the class.
  194. *
  195. * @param string $rootNamespace
  196. * @return string
  197. */
  198. protected function getDefaultNamespace($rootNamespace)
  199. {
  200. return $rootNamespace;
  201. }
  202. /**
  203. * Determine if the class already exists.
  204. *
  205. * @param string $rawName
  206. * @return bool
  207. */
  208. protected function alreadyExists($rawName)
  209. {
  210. return $this->files->exists($this->getPath($this->qualifyClass($rawName)));
  211. }
  212. /**
  213. * Build the directory for the class if necessary.
  214. *
  215. * @param string $path
  216. * @return string
  217. */
  218. protected function makeDirectory($path)
  219. {
  220. if (! $this->files->isDirectory(dirname($path))) {
  221. $this->files->makeDirectory(dirname($path), 0777, true, true);
  222. }
  223. return $path;
  224. }
  225. /**
  226. * Build the class with the given name.
  227. *
  228. * @param string $name
  229. * @return string
  230. *
  231. * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
  232. */
  233. protected function buildClass($name)
  234. {
  235. $stub = $this->files->get($this->getStub());
  236. return $this->replaceNamespace($stub, $name)->replaceClass($stub, $name);
  237. }
  238. /**
  239. * Replace the namespace for the given stub.
  240. *
  241. * @param string $stub
  242. * @param string $name
  243. * @return \Illuminate\Console\GeneratorCommand
  244. */
  245. protected function replaceNamespace(&$stub, $name)
  246. {
  247. $searches = [
  248. ['DummyNamespace', 'DummyRootNamespace', 'NamespacedDummyUserModel'],
  249. ['{{ namespace }}', '{{ rootNamespace }}', '{{ namespacedUserModel }}'],
  250. ['{{namespace}}', '{{rootNamespace}}', '{{namespacedUserModel}}'],
  251. ];
  252. foreach ($searches as $search) {
  253. $stub = str_replace(
  254. $search,
  255. [$this->getNamespace($name), $this->rootNamespace(), $this->userProviderModel()],
  256. $stub
  257. );
  258. }
  259. return $this;
  260. }
  261. /**
  262. * Get the full namespace for a given class, without the class name.
  263. *
  264. * @param string $name
  265. * @return string
  266. */
  267. protected function getNamespace($name)
  268. {
  269. return trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
  270. }
  271. /**
  272. * Replace the class name for the given stub.
  273. *
  274. * @param string $stub
  275. * @param string $name
  276. * @return string
  277. */
  278. protected function replaceClass($stub, $name)
  279. {
  280. $class = str_replace($this->getNamespace($name).'\\', '', $name);
  281. return str_replace(['DummyClass', '{{ class }}', '{{class}}'], $class, $stub);
  282. }
  283. /**
  284. * Alphabetically sorts the imports for the given stub.
  285. *
  286. * @param string $stub
  287. * @return string
  288. */
  289. protected function sortImports($stub)
  290. {
  291. if (preg_match('/(?P<imports>(?:use [^;]+;$\n?)+)/m', $stub, $match)) {
  292. $imports = explode("\n", trim($match['imports']));
  293. sort($imports);
  294. return str_replace(trim($match['imports']), implode("\n", $imports), $stub);
  295. }
  296. return $stub;
  297. }
  298. /**
  299. * Get the desired class name from the input.
  300. *
  301. * @return string
  302. */
  303. protected function getNameInput()
  304. {
  305. return trim($this->argument('name'));
  306. }
  307. /**
  308. * Get the model for the default guard's user provider.
  309. *
  310. * @return string|null
  311. */
  312. protected function userProviderModel()
  313. {
  314. $config = $this->laravel['config'];
  315. $provider = $config->get('auth.guards.'.$config->get('auth.defaults.guard').'.provider');
  316. return $config->get("auth.providers.{$provider}.model");
  317. }
  318. /**
  319. * Checks whether the given name is reserved.
  320. *
  321. * @param string $name
  322. * @return bool
  323. */
  324. protected function isReservedName($name)
  325. {
  326. $name = strtolower($name);
  327. return in_array($name, $this->reservedNames);
  328. }
  329. /**
  330. * Get the first view directory path from the application configuration.
  331. *
  332. * @param string $path
  333. * @return string
  334. */
  335. protected function viewPath($path = '')
  336. {
  337. $views = $this->laravel['config']['view.paths'][0] ?? resource_path('views');
  338. return $views.($path ? DIRECTORY_SEPARATOR.$path : $path);
  339. }
  340. /**
  341. * Get the console command arguments.
  342. *
  343. * @return array
  344. */
  345. protected function getArguments()
  346. {
  347. return [
  348. ['name', InputArgument::REQUIRED, 'The name of the class'],
  349. ];
  350. }
  351. /**
  352. * Get the root namespace for the class.
  353. *
  354. * @return string
  355. */
  356. protected function rootNamespace()
  357. {
  358. return $this->getDefaultNamespace(null);
  359. }
  360. /**
  361. * Get the destination class path.
  362. *
  363. * @param string $name
  364. * @return string
  365. */
  366. protected function getPath($name)
  367. {
  368. return Helper::guessClassFileName($name);
  369. }
  370. /**
  371. * @return string
  372. */
  373. protected function getBaseDir()
  374. {
  375. if ($this->baseDirectory) {
  376. return trim(base_path($this->baseDirectory), '/');
  377. }
  378. if ($this->hasOption('base') && $this->option('base')) {
  379. return trim(base_path($this->option('base')), '/');
  380. }
  381. return $this->laravel['path'];
  382. }
  383. /**
  384. * @return void
  385. */
  386. protected function askBaseDirectory()
  387. {
  388. if (! Str::startsWith(config('admin.route.namespace'), 'App')) {
  389. $dir = explode('\\', config('admin.route.namespace'))[0];
  390. $this->baseDirectory = trim($this->ask('Please enter the application path', Helper::slug($dir)));
  391. }
  392. }
  393. }