OptionFactory   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 24
dl 0
loc 50
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B fromArg() 0 43 8
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\Exception\InvalidArgumentException;
18
use Valkyrja\Cli\Interaction\Option\Option;
19
20
use function strlen;
21
22
/**
23
 * Class OptionFactory.
24
 *
25
 * @author Melech Mizrachi
26
 */
27
abstract class OptionFactory
28
{
29
    /**
30
     * @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...
31
     *
32
     * @return Option[]
33
     */
34
    public static function fromArg(string $arg): array
35
    {
36
        if (! str_starts_with($arg, '-')) {
37
            throw new InvalidArgumentException('Options must begin with either a `-` or `--`');
38
        }
39
40
        $type = str_starts_with($arg, '--')
41
            ? OptionType::LONG
42
            : OptionType::SHORT;
43
44
        $parts = explode('=', $arg);
45
        $name  = trim($parts[0], '- ');
46
        $value = $parts[1] ?? null;
47
48
        if ($value === '') {
49
            $value = null;
50
        }
51
52
        if ($type === OptionType::SHORT && strlen($name) > 1) {
53
            if ($value !== null) {
54
                throw new InvalidArgumentException('Cannot combine multiple options and include a value');
55
            }
56
57
            $options = [];
58
59
            foreach (str_split($name) as $item) {
60
                /** @var non-empty-string $item */
61
                $options[] = new Option(
62
                    name: $item,
63
                    type: $type
64
                );
65
            }
66
67
            return $options;
68
        }
69
70
        /** @var non-empty-string $name */
71
72
        return [
73
            new Option(
74
                name: $name,
75
                value: $value,
76
                type: $type
77
            ),
78
        ];
79
    }
80
}
81