Command.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Webman\Console;
  3. use RuntimeException;
  4. use Symfony\Component\Console\Application;
  5. use Symfony\Component\Console\Command\Command as Commands;
  6. use support\Container;
  7. class Command extends Application
  8. {
  9. public function installInternalCommands()
  10. {
  11. $this->installCommands(__DIR__ . '/Commands', 'Webman\Console\Commands');
  12. }
  13. public function installCommands($path, $namspace = 'app\command')
  14. {
  15. $dir_iterator = new \RecursiveDirectoryIterator($path);
  16. $iterator = new \RecursiveIteratorIterator($dir_iterator);
  17. foreach ($iterator as $file) {
  18. /** @var \SplFileInfo $file */
  19. if (strpos($file->getFilename(), '.') === 0) {
  20. continue;
  21. }
  22. if ($file->getExtension() !== 'php') {
  23. continue;
  24. }
  25. // abc\def.php
  26. $relativePath = str_replace(str_replace('/', '\\', $path . '\\'), '', str_replace('/', '\\', $file->getRealPath()));
  27. // app\command\abc
  28. $realNamespace = trim($namspace . '\\' . trim(dirname(str_replace('\\', DIRECTORY_SEPARATOR, $relativePath)), '.'), '\\');
  29. $realNamespace = str_replace('/', '\\', $realNamespace);
  30. // app\command\doc\def
  31. $class_name = trim($realNamespace . '\\' . $file->getBasename('.php'), '\\');
  32. if (!class_exists($class_name) || !is_a($class_name, Commands::class, true)) {
  33. continue;
  34. }
  35. $reflection = new \ReflectionClass($class_name);
  36. if ($reflection->isAbstract()) {
  37. continue;
  38. }
  39. $properties = $reflection->getStaticProperties();
  40. $name = $properties['defaultName'] ?? null;
  41. if (!$name) {
  42. throw new RuntimeException("Command {$class_name} has no defaultName");
  43. }
  44. $description = $properties['defaultDescription'] ?? '';
  45. $command = Container::get($class_name);
  46. $command->setName($name)->setDescription($description);
  47. $this->add($command);
  48. }
  49. }
  50. }