OptionFactory::fromArg()   B
last analyzed

Complexity

Conditions 8
Paths 17

Size

Total Lines 43
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 43
rs 8.4444
c 0
b 0
f 0
cc 8
nc 17
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Valkyrja Framework package.
7
 *
8
 * (c) Melech Mizrachi <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Valkyrja\Cli\Interaction\Factory;
15
16
use Valkyrja\Cli\Interaction\Enum\OptionType;
17
use Valkyrja\Cli\Interaction\Option\Option;
18
use Valkyrja\Cli\Interaction\Throwable\Exception\InvalidArgumentException;
19
20
use function strlen;
21
22
abstract class OptionFactory
23
{
24
    /**
25
     * @param non-empty-string $arg The arg
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
26
     *
27
     * @return Option[]
28
     */
29
    public static function fromArg(string $arg): array
30
    {
31
        if (! str_starts_with($arg, '-')) {
32
            throw new InvalidArgumentException('Options must begin with either a `-` or `--`');
33
        }
34
35
        $type = str_starts_with($arg, '--')
36
            ? OptionType::LONG
37
            : OptionType::SHORT;
38
39
        $parts = explode('=', $arg);
40
        $name  = trim($parts[0], '- ');
41
        $value = $parts[1] ?? null;
42
43
        if ($value === '') {
44
            $value = null;
45
        }
46
47
        if ($type === OptionType::SHORT && strlen($name) > 1) {
48
            if ($value !== null) {
49
                throw new InvalidArgumentException('Cannot combine multiple options and include a value');
50
            }
51
52
            $options = [];
53
54
            foreach (str_split($name) as $item) {
55
                /** @var non-empty-string $item */
56
                $options[] = new Option(
57
                    name: $item,
58
                    type: $type
59
                );
60
            }
61
62
            return $options;
63
        }
64
65
        /** @var non-empty-string $name */
66
67
        return [
68
            new Option(
69
                name: $name,
70
                value: $value,
71
                type: $type
72
            ),
73
        ];
74
    }
75
}
76