Conditions | 12 |
Paths | 36 |
Total Lines | 41 |
Code Lines | 24 |
Lines | 0 |
Ratio | 0 % |
Tests | 28 |
CRAP Score | 12 |
Changes | 3 | ||
Bugs | 1 | 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 |
||
8 | 10 | protected function export() { |
|
9 | 10 | $cols = func_get_args(); |
|
10 | |||
11 | // add cols |
||
12 | 10 | if (method_exists($this, 'hasRef') && $this->hasRef()) { |
|
|
|||
13 | 6 | $cols = array_merge(['$ref'], $cols); |
|
14 | 6 | } |
|
15 | |||
16 | // flatten array |
||
17 | 10 | $fields = []; |
|
18 | array_walk_recursive($cols, function ($a) use (&$fields) { $fields[] = $a; }); |
||
19 | |||
20 | 10 | $out = []; |
|
21 | 10 | $refl = new \ReflectionClass(get_class($this)); |
|
22 | |||
23 | 10 | foreach ($fields as $field) { |
|
24 | 10 | if ($field == 'tags') { |
|
25 | 7 | $val = $this->exportTags(); |
|
26 | 7 | } else { |
|
27 | 10 | $prop = $refl->getProperty($field == '$ref' ? 'ref' : $field); |
|
28 | 10 | $prop->setAccessible(true); |
|
29 | 10 | $val = $prop->getValue($this); |
|
30 | |||
31 | 10 | if ($val instanceof Collection) { |
|
32 | 10 | $val = $this->exportRecursiveArray($val->toArray()); |
|
33 | 10 | } else if (method_exists($val, 'toArray')) { |
|
34 | 10 | $val = $val->toArray(); |
|
35 | 10 | } |
|
36 | } |
||
37 | |||
38 | 10 | if ($field == 'required' && is_bool($val) || !empty($val)) { |
|
39 | 8 | $out[$field] = $val; |
|
40 | 8 | } |
|
41 | 10 | } |
|
42 | |||
43 | 10 | if (method_exists($this, 'getExtensions')) { |
|
44 | 10 | $out = array_merge($out, $this->getExtensions()->toArray()); |
|
45 | 10 | } |
|
46 | |||
47 | 10 | return $out; |
|
48 | } |
||
49 | |||
59 |
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: