This repository has been archived by the owner on Apr 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommandFactory.php
78 lines (66 loc) · 2.12 KB
/
CommandFactory.php
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
<?php
/**
* Copyright (C) GrizzIT, Inc. All rights reserved.
* See LICENSE for license details.
*/
namespace Ulrack\Transaction\Factory;
use Ulrack\Transaction\Component\Command;
use Ulrack\Transaction\Common\CommandInterface;
class CommandFactory
{
/**
* Creates a CLI command request.
*
* @param array $arguments The arguments passed to the command line.
*
* @return CommandInterface
*/
public static function create(array $arguments): CommandInterface
{
return new Command(
...static::prepareArguments(
$arguments
)
);
}
/**
* Prepare the CLI arguments.
*
* @return array
*/
private static function prepareArguments(array $arguments): array
{
// Strip the script
array_shift($arguments);
$command = array_shift($arguments);
$flags = [];
$options = [];
$parameters = [];
while ($argument = array_shift($arguments)) {
// First find out if there is a flag or parameter passed.
if (substr($argument, 0, 1) === '-') {
// The --parameter=value markdown is used
if (strpos($argument, '=') > 0) {
$expArg = explode('=', $argument);
$parameters[ltrim($expArg[0], '-')] = $expArg[1];
continue;
}
// No subsequent value starting without a "-"
// It must be a flag
if (empty($arguments[0])
|| substr($arguments[0], 0, 1) === '-') {
$flags[] = ltrim($argument, '-');
continue;
}
// There was a subsequent value starting without a "-"
// It counts as a parameter
$argument = ltrim($argument, '-');
$parameters[$argument] = array_shift($arguments);
continue;
}
// Additional arguments go into the options array
$options[] = $argument;
}
return [$command, $parameters, $options, $flags];
}
}