Conditions | 5 |
Paths | 5 |
Total Lines | 52 |
Code Lines | 22 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 1 |
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 |
||
66 | function vnsprintf($format, $args) |
||
67 | { |
||
68 | // we need to find all of the named parameters to expand |
||
69 | $regex = "|(?<!%)(?:%)([^0-9].+)(?:\\\$)|U"; |
||
70 | |||
71 | $matches = []; |
||
72 | $matchCount = preg_match_all($regex, $format, $matches, PREG_OFFSET_CAPTURE); |
||
73 | if ($matchCount === 0) { |
||
74 | // nothing to do |
||
75 | return vsprintf($format, $args); |
||
76 | } |
||
77 | |||
78 | // if we get here, then we have some matches to expand |
||
79 | // we're going to add them to the end of this array |
||
80 | $messageData = $args; |
||
81 | |||
82 | // this will keep track of where we've added the data |
||
83 | $nextData = count($messageData); |
||
84 | $paramKeys = array_fill_keys(array_keys($args), -1); |
||
85 | |||
86 | // this will keep track of how we've shrunk the format string |
||
87 | $formatChange = 0; |
||
88 | |||
89 | // transform the named parameters into offset parameters |
||
90 | foreach ($matches[1] as $match) { |
||
91 | // what is the named parameter? |
||
92 | $paramName = $match[0]; |
||
93 | |||
94 | // make sure the named parameter exists in our original data |
||
95 | if (!isset($paramKeys[$paramName])) { |
||
96 | throw new InvalidArgumentException("vnsprintf: named format-string parameter " . $paramName . " is not provided in \$args array"); |
||
97 | } |
||
98 | // have we already assigned it a place in $messageData? |
||
99 | // in case a named parameter appears multiple times in the format string |
||
100 | if ($paramKeys[$paramName] === -1) { |
||
101 | // no - it needs a home |
||
102 | $messageData[$nextData] =& $args[$paramName]; |
||
103 | $paramKeys[$paramName] = $nextData; |
||
104 | $nextData++; |
||
105 | } |
||
106 | // convert the named parameter in the format string into a positional |
||
107 | // parameter into $messageData |
||
108 | $paramOffset = $paramKeys[$paramName] + 1; |
||
109 | $format = substr_replace($format, $paramOffset, $formatChange + $match[1], strlen($paramName)); |
||
110 | |||
111 | // how much did we shrink / grow the format string by? |
||
112 | $formatChange = $formatChange - strlen($paramName) + strlen($paramOffset); |
||
113 | } |
||
114 | |||
115 | // all done |
||
116 | return vsprintf($format, $messageData); |
||
117 | } |
||
118 | |||
120 |