AdminCommand.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. namespace Dcat\Admin\Console;
  3. use Dcat\Admin\Admin;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\Artisan;
  6. use Illuminate\Support\Str;
  7. class AdminCommand extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'admin';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = 'List all admin commands';
  21. /**
  22. * @var string
  23. */
  24. public static $logo = <<<LOGO
  25. ____ ______ ___ ______ ___ ____ __ ___ ____ _ __
  26. / __ \ / ____// | /_ __/ / | / __ \ / |/ // _// | / /
  27. / / / // / / /| | / / / /| | / / / // /|_/ / / / / |/ /
  28. / /_/ // /___ / ___ | / / / ___ | / /_/ // / / /_/ / / /| /
  29. /_____/ \____//_/ |_|/_/ /_/ |_|/_____//_/ /_//___//_/ |_/
  30. LOGO;
  31. /**
  32. * Execute the console command.
  33. */
  34. public function handle()
  35. {
  36. $this->line(static::$logo);
  37. $this->line(Admin::longVersion());
  38. $this->comment('');
  39. $this->comment('Available commands:');
  40. $this->listAdminCommands();
  41. }
  42. /**
  43. * List all admin commands.
  44. *
  45. * @return void
  46. */
  47. protected function listAdminCommands()
  48. {
  49. $commands = collect(Artisan::all())->mapWithKeys(function ($command, $key) {
  50. if (Str::startsWith($key, 'admin:')) {
  51. return [$key => $command];
  52. }
  53. return [];
  54. })->toArray();
  55. $width = $this->getColumnWidth($commands);
  56. /** @var Command $command */
  57. foreach ($commands as $command) {
  58. $this->line(sprintf(" %-{$width}s %s", $command->getName(), $command->getDescription()));
  59. }
  60. }
  61. /**
  62. * @param (Command|string)[] $commands
  63. *
  64. * @return int
  65. */
  66. private function getColumnWidth(array $commands)
  67. {
  68. $widths = [];
  69. foreach ($commands as $command) {
  70. $widths[] = static::strlen($command->getName());
  71. foreach ($command->getAliases() as $alias) {
  72. $widths[] = static::strlen($alias);
  73. }
  74. }
  75. return $widths ? max($widths) + 2 : 0;
  76. }
  77. /**
  78. * Returns the length of a string, using mb_strwidth if it is available.
  79. *
  80. * @param string $string The string to check its length
  81. *
  82. * @return int The length of the string
  83. */
  84. public static function strlen($string)
  85. {
  86. if (false === $encoding = mb_detect_encoding($string, null, true)) {
  87. return strlen($string);
  88. }
  89. return mb_strwidth($string, $encoding);
  90. }
  91. }