| Conditions | 14 |
| Paths | 1 |
| Total Lines | 60 |
| Code Lines | 35 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 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 |
||
| 117 | private function getDefaultValidator() |
||
| 118 | { |
||
| 119 | $choices = $this->choices; |
||
| 120 | $errorMessage = $this->errorMessage; |
||
| 121 | $multiselect = $this->multiselect; |
||
| 122 | $isAssoc = $this->isAssoc($choices); |
||
| 123 | |||
| 124 | return function ($selected) use ($choices, $errorMessage, $multiselect, $isAssoc) { |
||
| 125 | // Collapse all spaces. |
||
| 126 | $selectedChoices = str_replace(' ', '', $selected); |
||
| 127 | |||
| 128 | if ($multiselect) { |
||
| 129 | // Check for a separated comma values |
||
| 130 | if (!preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $selectedChoices, $matches)) { |
||
| 131 | throw new InvalidArgumentException(sprintf($errorMessage, $selected)); |
||
| 132 | } |
||
| 133 | $selectedChoices = explode(',', $selectedChoices); |
||
| 134 | } else { |
||
| 135 | $selectedChoices = array($selected); |
||
| 136 | } |
||
| 137 | |||
| 138 | $multiselectChoices = array(); |
||
| 139 | foreach ($selectedChoices as $value) { |
||
| 140 | $results = array(); |
||
| 141 | foreach ($choices as $key => $choice) { |
||
| 142 | if ($choice === $value) { |
||
| 143 | $results[] = $key; |
||
| 144 | } |
||
| 145 | } |
||
| 146 | |||
| 147 | if (count($results) > 1) { |
||
| 148 | throw new InvalidArgumentException(sprintf('The provided answer is ambiguous. Value should be one of %s.', implode(' or ', $results))); |
||
| 149 | } |
||
| 150 | |||
| 151 | $result = array_search($value, $choices); |
||
| 152 | |||
| 153 | if (!$isAssoc) { |
||
| 154 | if (false !== $result) { |
||
| 155 | $result = $choices[$result]; |
||
| 156 | } elseif (isset($choices[$value])) { |
||
| 157 | $result = $choices[$value]; |
||
| 158 | } |
||
| 159 | } elseif (false === $result && isset($choices[$value])) { |
||
| 160 | $result = $value; |
||
| 161 | } |
||
| 162 | |||
| 163 | if (false === $result) { |
||
| 164 | throw new InvalidArgumentException(sprintf($errorMessage, $value)); |
||
| 165 | } |
||
| 166 | |||
| 167 | $multiselectChoices[] = (string) $result; |
||
| 168 | } |
||
| 169 | |||
| 170 | if ($multiselect) { |
||
| 171 | return $multiselectChoices; |
||
| 172 | } |
||
| 173 | |||
| 174 | return current($multiselectChoices); |
||
| 175 | }; |
||
| 176 | } |
||
| 177 | } |
||
| 178 |