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