-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCommandFactory.php
More file actions
113 lines (97 loc) · 3.1 KB
/
CommandFactory.php
File metadata and controls
113 lines (97 loc) · 3.1 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
declare(strict_types=1);
namespace Smeghead\PhpVariableHardUsage\Option;
use Smeghead\PhpVariableHardUsage\Command\CheckCommand;
use Smeghead\PhpVariableHardUsage\Command\CommandInterface;
use Smeghead\PhpVariableHardUsage\Command\HelpCommand;
use Smeghead\PhpVariableHardUsage\Command\ScopesCommand;
use Smeghead\PhpVariableHardUsage\Command\SingleCommand;
use Smeghead\PhpVariableHardUsage\Command\VersionCommand;
/**
* コマンドライン引数を解析し、適切なコマンドと引数を生成するクラス
*/
final class CommandFactory
{
/** @var list<string> */
private const array SUB_COMMANDS = [
'single',
'scopes',
'check',
];
/**
* @param array<string, string|bool> $options オプション
* @param array<string> $argv コマンドライン引数
*/
public function __construct(private readonly array $options, private readonly array $argv)
{
}
/**
* コマンドライン引数を解析し、コマンドと引数を返す
*/
public function create(): CommandInterface
{
// ヘルプと バージョン表示は特別処理
if (array_key_exists('help', $this->options)) {
return new HelpCommand();
}
if (array_key_exists('version', $this->options)) {
return new VersionCommand();
}
if (count($this->argv) === 0) {
return new HelpCommand();
}
$paths = $this->argv;
if (in_array($this->argv[0], self::SUB_COMMANDS, true)) {
$subCommand = $this->argv[0];
$paths = array_slice($this->argv, 1);
// コマンドに応じた処理
switch ($subCommand) {
case 'single':
return $this->parseSingleCommand($paths);
case 'scopes':
return $this->parseScopesCommand($paths);
case 'check':
return $this->parseCheckCommand($paths);
}
}
return new SingleCommand($paths[0]);
}
/**
* 単一ファイルコマンドを解析
*
* @param list<string> $paths
*/
private function parseSingleCommand(array $paths): CommandInterface
{
if (empty($paths)) {
return new HelpCommand();
}
return new SingleCommand($paths[0]);
}
/**
* スコープコマンドを解析
* @param list<string> $paths
*/
private function parseScopesCommand(array $paths): CommandInterface
{
if (empty($paths)) {
return new HelpCommand();
}
return new ScopesCommand($paths);
}
/**
* チェックコマンドを解析
* @param list<string> $paths
*/
private function parseCheckCommand(array $paths): CommandInterface
{
if (empty($paths)) {
return new HelpCommand();
}
$threshold = $this->options['threshold'] ?? null;
if (isset($threshold)) {
$threshold = (int) $threshold;
}
return new CheckCommand($paths, $threshold);
}
}