flush
[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 $this->help($prog);
32 exit;
33 }
34 if (!empty($errs)) {
35 foreach ($errs as $err) {
36 fprintf(STDERR, "ERROR: %s\n", $err);
37 exit(-1);
38 }
39 }
40
41 if ($this->args["ngrok"]) {
42 $exec(Cli\Ngrok::class);
43 }
44 if ($this->args["initdb"]) {
45 $exec(Cli\Initdb::class);
46 }
47 if ($this->args["gen-models"]) {
48 $exec(Cli\GenModels::class);
49 }
50 }
51
52 function getConfig() {
53 return $this->config;
54 }
55
56 /**
57 * Output command line help message
58 * @param string $prog
59 */
60 public function help($prog) {
61 printf("Usage:\n\n \$ %s", $prog);
62
63 $flags = [];
64 $required = [];
65 $optional = [];
66 foreach ($this->args->getSpec() as $spec) {
67 if ($spec[3] & Args::REQARG) {
68 if ($spec[3] & Args::REQUIRED) {
69 $required[] = $spec;
70 } else {
71 $optional[] = $spec;
72 }
73 } else {
74 $flags[] = $spec;
75 }
76 }
77
78 if ($flags) {
79 printf(" [-%s]", implode("", array_column($flags, 0)));
80 }
81 foreach ($required as $req) {
82 printf(" -%s <arg>", $req[0]);
83 }
84 if ($optional) {
85 printf(" [-%s <arg>]", implode("|-", array_column($optional, 0)));
86 }
87 printf("\n\n");
88 $spc = $this->args->getSpec();
89 $max = $spc ? max(array_map("strlen", array_column($spc, 1))) : 0;
90 $max += $max % 8 + 2;
91 foreach ($spc as $spec) {
92 if (isset($spec[0])) {
93 printf(" -%s|", $spec[0]);
94 } else {
95 printf(" ");
96 }
97 printf("--%s ", $spec[1]);
98 if ($spec[3] & Args::REQARG) {
99 printf("<arg> ");
100 } elseif ($spec[3] & Args::OPTARG) {
101 printf("[<arg>]");
102 } else {
103 printf(" ");
104 }
105 printf("%s%s", str_repeat(" ", $max-strlen($spec[1])+3*!isset($spec[0])), $spec[2]);
106 if ($spec[3] & Args::REQUIRED) {
107 printf(" (REQUIRED)");
108 }
109 if (isset($spec[4])) {
110 printf(" [%s]", $spec[4]);
111 }
112 printf("\n");
113 }
114 printf("\n");
115 }
116 }