-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathAbstractCommand.php
More file actions
80 lines (67 loc) · 2 KB
/
AbstractCommand.php
File metadata and controls
80 lines (67 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
namespace AwsBuild\Command;
abstract class AbstractCommand implements CommandInterface
{
protected bool $verbose = false;
private ?string $projectRoot;
public function __construct(?string $projectRoot = null)
{
$this->projectRoot = $projectRoot ?? dirname(__DIR__, 2);
}
public function execute(array $args): int
{
if (in_array('--help', $args, true) || in_array('-h', $args, true)) {
$name = $this->getName();
$this->output($name);
$this->output(str_repeat('-', strlen($name)));
$this->output($this->getDescription());
$this->output('');
$this->output('Usage:');
$this->output(' ' . $this->getUsage());
return 0;
}
if (in_array('--verbose', $args, true) || in_array('-v', $args, true)) {
$this->verbose = true;
}
return $this->doExecute($args);
}
abstract protected function doExecute(array $args): int;
protected function output(string $msg): void
{
fwrite(STDOUT, $msg . "\n");
}
protected function error(string $msg): void
{
fwrite(STDERR, "[ERROR] $msg\n");
}
protected function verbose(string $msg): void
{
if ($this->verbose) {
fwrite(STDOUT, $msg . "\n");
}
}
protected function parseOptions(array $args): array
{
$options = [];
foreach ($args as $arg) {
if (str_starts_with($arg, '--')) {
$arg = substr($arg, 2);
if (str_contains($arg, '=')) {
[$key, $value] = explode('=', $arg, 2);
$options[$key] = $value;
} else {
$options[$arg] = true;
}
}
}
return $options;
}
protected function getProjectRoot(): string
{
return $this->projectRoot;
}
protected static function getBuildDir(): string
{
return dirname(__DIR__);
}
}