This repository has been archived by the owner on Apr 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInputFactory.php
104 lines (85 loc) · 2.84 KB
/
InputFactory.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
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
<?php
/**
* Copyright (C) GrizzIT, Inc. All rights reserved.
* See LICENSE for license details.
*/
namespace Ulrack\Command\Factory;
use Ulrack\Command\Component\Command\Input;
use Ulrack\Command\Common\Command\InputInterface;
use Ulrack\Command\Common\Factory\InputFactoryInterface;
class InputFactory implements InputFactoryInterface
{
/**
* Creates a CLI command request.
*
* @param array $arguments The arguments passed to the command line.
*
* @return InputInterface
*/
public static function create(array $arguments): InputInterface
{
return new Input(
...static::prepareArguments(
$arguments
)
);
}
/**
* Prepare the CLI arguments.
*
* @param array $arguments
*
* @return array
*/
private static function prepareArguments(array $arguments): array
{
// Strip the script
array_shift($arguments);
$command = [];
$flags = [];
$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);
if (substr($expArg[0], -2, 2) === '[]') {
// Array markdown is used.
$parameters[rtrim(
ltrim($expArg[0], '-'),
'[]'
)][] = $expArg[1];
continue;
}
$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, '-');
if (substr($argument, -2, 2) === '[]') {
// Array markdown is used.
$parameters[rtrim($argument, '[]')][] = array_shift(
$arguments
);
continue;
}
$parameters[$argument] = array_shift($arguments);
continue;
}
// Additional arguments go into the command array
$command[] = $argument;
}
return [$command, $parameters, $flags];
}
}