Conditions | 13 |
Paths | 36 |
Total Lines | 41 |
Lines | 0 |
Ratio | 0 % |
Tests | 28 |
CRAP Score | 13 |
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 |
||
9 | 11 | protected function export() { |
|
10 | 11 | $cols = func_get_args(); |
|
11 | |||
12 | // add cols |
||
13 | 11 | if (method_exists($this, 'hasRef') && $this->hasRef()) { |
|
|
|||
14 | 6 | $cols = array_merge(['$ref'], $cols); |
|
15 | 6 | } |
|
16 | |||
17 | // flatten array |
||
18 | 11 | $fields = []; |
|
19 | array_walk_recursive($cols, function ($a) use (&$fields) { $fields[] = $a; }); |
||
20 | |||
21 | 11 | $out = []; |
|
22 | 11 | $refl = new \ReflectionClass(get_class($this)); |
|
23 | |||
24 | 11 | foreach ($fields as $field) { |
|
25 | 11 | if ($field == 'tags') { |
|
26 | 8 | $val = $this->exportTags(); |
|
27 | 8 | } else { |
|
28 | 11 | $prop = $refl->getProperty($field == '$ref' ? 'ref' : $field); |
|
29 | 11 | $prop->setAccessible(true); |
|
30 | 11 | $val = $prop->getValue($this); |
|
31 | |||
32 | 11 | if ($val instanceof Collection) { |
|
33 | 11 | $val = CollectionUtils::toArrayRecursive($val); |
|
34 | 11 | } else if (is_object($val) && method_exists($val, 'toArray')) { |
|
35 | 11 | $val = $val->toArray(); |
|
36 | 11 | } |
|
37 | } |
||
38 | |||
39 | 11 | if ($field == 'required' && is_bool($val) || !empty($val)) { |
|
40 | 9 | $out[$field] = $val; |
|
41 | 9 | } |
|
42 | 11 | } |
|
43 | |||
44 | 11 | if (method_exists($this, 'getExtensions')) { |
|
45 | 11 | $out = array_merge($out, $this->getExtensions()->toArray()); |
|
46 | 11 | } |
|
47 | |||
48 | 11 | return $out; |
|
49 | } |
||
50 | |||
52 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the parent class: