cli: virtual commands options
[pharext/pharext.org] / app / Cli.php
1 <?php
2
3 namespace app;
4
5 use pharext\Cli\Args;
6
7 class Cli
8 {
9 /**
10 * @var \app\Config
11 */
12 private $config;
13
14 /**
15 * @var \pharext\Cli\Args
16 */
17 private $args;
18
19 function __construct(Config $config, Args $args) {
20 $this->config = $config;
21 $this->args = $args;
22 }
23
24 function __invoke($argc, array $argv, callable $exec) {
25 $prog = array_shift($argv);
26 foreach ($this->args->parse(--$argc, $argv) as $error) {
27 $errs[] = $error;
28 }
29
30 if ($this->args["help"] || !array_filter($this->args->toArray())) {
31 //var_dump($this->args->toArray(), $this->args[0]);
32 $this->help($prog);
33 exit;
34 }
35 if (!empty($errs)) {
36 foreach ($errs as $err) {
37 fprintf(STDERR, "ERROR: %s\n", $err);
38 exit(-1);
39 }
40 }
41
42 switch($this->args[0]) {
43 case "ngrok":
44 $exec(Cli\Ngrok::class);
45 break;
46 case "initdb":
47 $exec(Cli\Initdb::class);
48 break;
49 case "gen-models":
50 $exec(Cli\GenModels::class);
51 break;
52 }
53 }
54
55 function getConfig() {
56 return $this->config;
57 }
58
59 /**
60 * Output command line help message
61 * @param string $prog
62 */
63 public function help($prog) {
64 return print new Args\Help($prog, $this->args);
65 printf("Usage:\n\n \$ %s", $prog);
66
67 $flags = [];
68 $required = [];
69 $optional = [];
70 foreach ($this->args->getSpec() as $spec) {
71 if ($spec[3] & Args::REQARG) {
72 if ($spec[3] & Args::REQUIRED) {
73 $required[] = $spec;
74 } else {
75 $optional[] = $spec;
76 }
77 } else {
78 $flags[] = $spec;
79 }
80 }
81
82 if ($flags) {
83 printf(" [-%s]", implode("", array_column($flags, 0)));
84 }
85 foreach ($required as $req) {
86 printf(" -%s <arg>", $req[0]);
87 }
88 if ($optional) {
89 printf(" [-%s <arg>]", implode("|-", array_column($optional, 0)));
90 }
91 printf("\n\n");
92 $spc = $this->args->getSpec();
93 $max = $spc ? max(array_map("strlen", array_column($spc, 1))) : 0;
94 $max += $max % 8 + 2;
95 foreach ($spc as $spec) {
96 if (isset($spec[0])) {
97 printf(" -%s|", $spec[0]);
98 } else {
99 printf(" ");
100 }
101 printf("--%s ", $spec[1]);
102 if ($spec[3] & Args::REQARG) {
103 printf("<arg> ");
104 } elseif ($spec[3] & Args::OPTARG) {
105 printf("[<arg>]");
106 } else {
107 printf(" ");
108 }
109 printf("%s%s", str_repeat(" ", $max-strlen($spec[1])+3*!isset($spec[0])), $spec[2]);
110 if ($spec[3] & Args::REQUIRED) {
111 printf(" (REQUIRED)");
112 }
113 if (isset($spec[4])) {
114 printf(" [%s]", $spec[4]);
115 }
116 printf("\n");
117 }
118 printf("\n");
119 }
120 }