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