Argv.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * 命令行参数
  4. *
  5. * @author mybsdc <[email protected]>
  6. * @date 2020/1/3
  7. * @time 16:32
  8. */
  9. namespace Luolongfei\Libs;
  10. class Argv extends Base
  11. {
  12. /**
  13. * @var array 所有命令行参数
  14. */
  15. public $allArgs = [];
  16. protected function init()
  17. {
  18. $this->parseAllArgs();
  19. if ($this->get('help') || $this->get('h')) {
  20. $desc = <<<FLL
  21. Description
  22. Params:
  23. -c: <string> 指定要实例化的类名。默认调用 FreeNom 类 Specifies the name of the class to instantiate. The default call to the FreeNom class
  24. -m: <string> 指定要调用的方法名(不支持静态方法)。默认调用 handle 方法 Specifies the name of the method to be called (static methods are not supported). The handle method is called by default
  25. -h: 显示说明 Help
  26. Example:
  27. $ php run -c=FreeNom -m=handle
  28. FLL;
  29. echo $desc;
  30. exit(0);
  31. }
  32. }
  33. /**
  34. * 获取命令行参数
  35. *
  36. * @param string $name
  37. * @param string $default
  38. *
  39. * @return mixed|string
  40. */
  41. public function get(string $name, string $default = '')
  42. {
  43. return $this->allArgs[$name] ?? $default;
  44. }
  45. /**
  46. * 解析所有命令行参数
  47. *
  48. * @return array
  49. */
  50. public function parseAllArgs()
  51. {
  52. global $argv;
  53. foreach ($argv as $a) { // Windows默认命令行无法正确传入使用引号括住的带空格参数,换个命令行终端就好,Linux不受影响
  54. if (preg_match('/^-{1,2}(?P<name>\w+)(?:=([\'"]|)(?P<val>[^\n\t\v\f\r\'"]+)\2)?$/i', $a, $m)) {
  55. $this->allArgs[$m['name']] = $m['val'] ?? true;
  56. }
  57. }
  58. return $this->allArgs;
  59. }
  60. }