CommandRouter.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace KarmaFW\App\Middlewares;
  3. use \KarmaFW\App\Request;
  4. use \KarmaFW\App\Response;
  5. use \KarmaFW\App\ResponseError404;
  6. use \KarmaFW\App\ResponseFile;
  7. class CommandRouter
  8. {
  9. protected $argv;
  10. public function __construct($argv=[])
  11. {
  12. $this->argv = $argv;
  13. }
  14. public function __invoke(Request $request, Response $response, callable $next)
  15. {
  16. $arguments = array_slice($this->argv, 0);
  17. $script_name = array_shift($arguments);
  18. $command_name = array_shift($arguments);
  19. if (in_array($command_name, ['-h', '--help', '-help'])) {
  20. $command_name = 'help';
  21. }
  22. $class_name = implode('', array_map('ucfirst', explode("_", $command_name)));
  23. if (! empty($class_name)) {
  24. $class_user = '\\App\\Commands\\' . $class_name;
  25. $class_fw = '\\KarmaFW\\Commands\\' . $class_name;
  26. if (class_exists($class_user)) {
  27. // User command
  28. $command = new $class_user($request, $response);
  29. $command->execute($arguments);
  30. } else if (class_exists($class_user . "Command")) {
  31. // User command
  32. $class_user .= "Command";
  33. $command = new $class_user($request, $response);
  34. $command->execute($arguments);
  35. } else if (class_exists($class_fw)) {
  36. // Framework command
  37. $command = new $class_fw($request, $response);
  38. $command->execute($arguments);
  39. } else if (class_exists($class_fw . "Command")) {
  40. // Framework command
  41. $class_fw .= "Command";
  42. $command = new $class_fw($request, $response);
  43. $command->execute($arguments);
  44. } else {
  45. $this->usage("invalid command : " . $command_name);
  46. }
  47. } else {
  48. $this->usage("missing command");
  49. }
  50. return $response;
  51. }
  52. protected function usage($error)
  53. {
  54. echo "PHP Console script" . PHP_EOL . PHP_EOL;
  55. echo "Usage: php console.php <command> [arguments]" . PHP_EOL . PHP_EOL;
  56. if ($error) {
  57. echo "Warning: " . $error . PHP_EOL;
  58. }
  59. }
  60. }