| Conditions | 13 |
| Paths | 100 |
| Total Lines | 51 |
| Lines | 0 |
| Ratio | 0 % |
| Tests | 0 |
| CRAP Score | 182 |
| 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 |
||
| 11 | static function lock($key, $seconds, callable $success, callable $error=null){ |
||
|
|
|||
| 12 | $key = 'lock:'.$key; |
||
| 13 | if(function_exists('apc_add')){ |
||
| 14 | $lock = new ApcLock(); |
||
| 15 | }else{ |
||
| 16 | $lock = new FileLock(); |
||
| 17 | } |
||
| 18 | try{ |
||
| 19 | if(!isset(self::$currentLock[$key])){ |
||
| 20 | self::$currentLock[$key] = 0; |
||
| 21 | } |
||
| 22 | if(self::$currentLock[$key] == 0){ //未加锁 |
||
| 23 | if(!$lock->lock($key, $seconds)){ //加锁失败 |
||
| 24 | if($error){ |
||
| 25 | return $error(); |
||
| 26 | } |
||
| 27 | return; |
||
| 28 | } |
||
| 29 | } |
||
| 30 | //嵌套加锁 |
||
| 31 | self::$currentLock[$key]++; |
||
| 32 | }catch (\Exception $e){ |
||
| 33 | if($error){ |
||
| 34 | return $error(); |
||
| 35 | } |
||
| 36 | return; |
||
| 37 | } |
||
| 38 | $res = null; |
||
| 39 | try{ |
||
| 40 | $res = $success(); |
||
| 41 | }catch (\Exception $e){ |
||
| 42 | self::$currentLock[$key]--; |
||
| 43 | if(self::$currentLock[$key] == 0){ |
||
| 44 | try{ |
||
| 45 | $lock->unlock($key); |
||
| 46 | }catch (\Exception $e){ |
||
| 47 | |||
| 48 | } |
||
| 49 | } |
||
| 50 | throw $e; |
||
| 51 | } |
||
| 52 | self::$currentLock[$key]--; |
||
| 53 | if(self::$currentLock[$key] == 0){ |
||
| 54 | try{ |
||
| 55 | $lock->unlock($key); |
||
| 56 | }catch (\Exception $e){ |
||
| 57 | |||
| 58 | } |
||
| 59 | } |
||
| 60 | return $res; |
||
| 61 | } |
||
| 62 | |||
| 65 | } |
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.