Setter::parse()   B
last analyzed

Complexity

Conditions 9
Paths 24

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 35
rs 8.0555
nc 24
nop 1
cc 9
1
<?php
2
3
namespace ConsoleArgs;
4
5
/**
6
 * Объект сеттеров
7
 * Отвечает за объявление сет-параметров команд
8
 */
9
class Setter implements Parameter
10
{
11
    public $names;
12
    public $separator;
13
    public $defaultValue;
14
    public $required;
15
    protected $locale;
16
17
    /**
18
     * Конструктор
19
     * 
20
     * @param string $name - имя сеттера
21
     * [@param string $separator = '='] - разделитель сеттера и значения
22
     * [@param string $defaultValue = null] - значение сеттера по умолчанию
23
     * [@param bool $required = false] - обязательно ли указание сеттера
24
     */
25
    public function __construct (string $name, string $separator = '=', string $defaultValue = null, bool $required = false)
26
    {
27
        $this->names        = [$name];
28
        $this->separator    = $separator;
29
        $this->defaultValue = $defaultValue;
30
        $this->required     = $required;
31
32
        $this->locale = new Locale;
33
    }
34
35
    /**
36
     * Установка локализации
37
     * 
38
     * @param Locale $locale - объект локализации
39
     * 
40
     * @return Param - возвращает сам себя
41
     */
42
    public function setLocale (Locale $locale): Param
43
    {
44
        $this->locale = $locale;
45
46
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type ConsoleArgs\Setter which is incompatible with the type-hinted return ConsoleArgs\Param.
Loading history...
47
    }
48
49
    /**
50
     * Добавление алиаса
51
     * 
52
     * @param string $name - алиас для добавления
53
     * 
54
     * @return Param - возвращает сам себя
55
     */
56
    public function addAliase (string $name)
57
    {
58
        if (array_search ($name, $this->names) !== false)
59
            throw new \Exception ($this->locale->aliase_exists_exception);
60
61
        $this->names[] = $name;
62
63
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type ConsoleArgs\Setter which is incompatible with the documented return type ConsoleArgs\Param.
Loading history...
64
    }
65
66
    /**
67
     * Парсер параметров
68
     * 
69
     * @param array &$args - массив аргументов для парсинга
70
     * 
71
     * Возвращает найденый параметр или массив найдёных параметров, если их было указано несколько
72
     */
73
    public function parse (array &$args)
74
    {
75
        $args = array_values ($args);
76
        $l    = strlen ($this->separator);
77
78
        foreach ($this->names as $name)
79
            foreach ($args as $id => $arg)
80
                if (substr ($arg, 0, ($pos = strlen ($name) + $l)) == $name . $this->separator)
81
                {
82
                    $param = [substr ($arg, $pos)];
83
84
                    unset ($args[$id]);
85
                    $args = array_values ($args);
86
87
                    try
88
                    {
89
                        while (($altParam = $this->parse ($args)) !== $this->defaultValue)
90
                        {
91
                            if (is_array ($altParam))
92
                                $param = array_merge ($param, $altParam);
93
    
94
                            else $param[] = $altParam;
95
                        }
96
                    }
97
98
                    catch (\Throwable $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
99
                    
100
                    return sizeof ($param) == 1 ?
101
                        $param[0] : $param;
102
                }
103
104
        if ($this->required)
105
            throw new \Exception (str_replace ('%param_name%', current ($this->names), $this->locale->undefined_param_exception));
106
107
        return $this->defaultValue;
108
    }
109
}
110