Conditions | 12 |
Paths | 9 |
Total Lines | 42 |
Code Lines | 24 |
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 |
||
34 | static function create($name, array $args, callable $callback) |
||
|
|||
35 | { |
||
36 | $class = static::reflectionClass($name); |
||
37 | |||
38 | if (!$class->constructor()) { |
||
39 | return $class->newInstanceWithoutConstructor(); |
||
40 | } |
||
41 | |||
42 | if ($args && !is_string(key($args))) { |
||
43 | return new $name(...$args); |
||
44 | } |
||
45 | |||
46 | $matched = []; |
||
47 | $params = $class->params(); |
||
48 | |||
49 | foreach($params as $param) { |
||
50 | if (isset($args[$param->name])) { |
||
51 | $matched[] = $args[$param->name]; |
||
52 | continue; |
||
53 | } |
||
54 | |||
55 | if ($param->isOptional()) { |
||
56 | $param->isDefaultValueAvailable() && |
||
57 | $matched[] = $param->getDefaultValue(); |
||
58 | continue; |
||
59 | } |
||
60 | |||
61 | if (null !== ($hint = $param->getClass()) && null !== $match = $callback($hint->name)) { |
||
62 | $matched[] = $match; |
||
63 | continue; |
||
64 | } |
||
65 | |||
66 | if (null !== $match = $callback($param->name)) { |
||
67 | $matched[] = $match; |
||
68 | continue; |
||
69 | } |
||
70 | |||
71 | Exception::runtime('Missing required parameter $' . $param->name . ' for ' . $name); |
||
72 | } |
||
73 | |||
74 | return new $name(...($params ? $matched : array_values($args))); |
||
75 | } |
||
76 | |||
111 |
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.