Conditions | 16 |
Paths | 1 |
Total Lines | 52 |
Code Lines | 36 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
46 | private function getDefaultValidator(): callable |
||
47 | { |
||
48 | $choices = $this->items; |
||
49 | $multiselect = $this->multiselect; |
||
50 | $errorMessage = 'Value "%s" is invalid'; |
||
51 | $isAssoc = (bool)\count(\array_filter(\array_keys($choices), '\is_string')); |
||
52 | |||
53 | return function ($selected) use ($choices, $errorMessage, $multiselect, $isAssoc) { |
||
54 | // Collapse all spaces. |
||
55 | $selectedChoices = \str_replace(' ', '', $selected); |
||
56 | if (!empty($this->helpText) && $selectedChoices === '?') { |
||
57 | return '?'; |
||
58 | } |
||
59 | if ($multiselect) { |
||
60 | // Check for a separated comma values |
||
61 | if (!preg_match('/^[^,]+(?:,[^,]+)*$/', $selectedChoices, $matches)) { |
||
62 | throw new InvalidArgumentException(sprintf($errorMessage, $selected)); |
||
63 | } |
||
64 | $selectedChoices = \explode(',', $selectedChoices); |
||
65 | } else { |
||
66 | $selectedChoices = array($selected); |
||
67 | } |
||
68 | $multiselectChoices = array(); |
||
69 | foreach ($selectedChoices as $value) { |
||
70 | $results = array(); |
||
71 | foreach ($choices as $key => $choice) { |
||
72 | if ($choice === $value) { |
||
73 | $results[] = $key; |
||
74 | } |
||
75 | } |
||
76 | if (\count($results) > 1) { |
||
77 | throw new InvalidArgumentException(sprintf('The provided answer is ambiguous. Value should be one of %s.', \implode(' or ', $results))); |
||
78 | } |
||
79 | $result = \array_search($value, $choices); |
||
80 | if (!$isAssoc) { |
||
81 | if (false !== $result) { |
||
82 | $result = $choices[$result]; |
||
83 | } elseif (isset($choices[$value])) { |
||
84 | $result = $choices[$value]; |
||
85 | } |
||
86 | } elseif (false === $result && isset($choices[$value])) { |
||
87 | $result = $value; |
||
88 | } |
||
89 | if (false === $result) { |
||
90 | throw new InvalidArgumentException(sprintf($errorMessage, $value)); |
||
91 | } |
||
92 | $multiselectChoices[] = (string) $result; |
||
93 | } |
||
94 | if ($multiselect) { |
||
95 | return $multiselectChoices; |
||
96 | } |
||
97 | return \current($multiselectChoices); |
||
98 | }; |
||
101 |