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 |
||
47 | private function getDefaultValidator(): callable |
||
48 | { |
||
49 | $choices = $this->items; |
||
50 | $multiselect = $this->multiselect; |
||
51 | $errorMessage = 'Value "%s" is invalid'; |
||
52 | $isAssoc = (bool)\count(\array_filter(\array_keys($choices), '\is_string')); |
||
53 | |||
54 | return function ($selected) use ($choices, $errorMessage, $multiselect, $isAssoc) { |
||
55 | // Collapse all spaces. |
||
56 | $selectedChoices = \str_replace(' ', '', $selected); |
||
57 | if (!empty($this->helpText) && $selectedChoices === '?') { |
||
58 | return '?'; |
||
59 | } |
||
60 | if ($multiselect) { |
||
61 | // Check for a separated comma values |
||
62 | if (!preg_match('/^[^,]+(?:,[^,]+)*$/', $selectedChoices, $matches)) { |
||
63 | throw new InvalidArgumentException(sprintf($errorMessage, $selected)); |
||
64 | } |
||
65 | $selectedChoices = \explode(',', $selectedChoices); |
||
66 | } else { |
||
67 | $selectedChoices = array($selected); |
||
68 | } |
||
69 | $multiselectChoices = array(); |
||
70 | foreach ($selectedChoices as $value) { |
||
71 | $results = array(); |
||
72 | foreach ($choices as $key => $choice) { |
||
73 | if ($choice === $value) { |
||
74 | $results[] = $key; |
||
75 | } |
||
76 | } |
||
77 | if (\count($results) > 1) { |
||
78 | throw new InvalidArgumentException(sprintf('The provided answer is ambiguous. Value should be one of %s.', \implode(' or ', $results))); |
||
79 | } |
||
80 | $result = \array_search($value, $choices); |
||
81 | if (!$isAssoc) { |
||
82 | if (false !== $result) { |
||
83 | $result = $choices[$result]; |
||
84 | } elseif (isset($choices[$value])) { |
||
85 | $result = $choices[$value]; |
||
86 | } |
||
87 | } elseif (false === $result && isset($choices[$value])) { |
||
88 | $result = $value; |
||
89 | } |
||
90 | if (false === $result) { |
||
91 | throw new InvalidArgumentException(sprintf($errorMessage, $value)); |
||
92 | } |
||
93 | $multiselectChoices[] = (string) $result; |
||
94 | } |
||
95 | if ($multiselect) { |
||
96 | return $multiselectChoices; |
||
97 | } |
||
98 | return \current($multiselectChoices); |
||
99 | }; |
||
102 |