Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 29 | class ProcessCacheLRU { |
||
| 30 | /** @var Array */ |
||
| 31 | protected $cache = []; // (key => prop => value) |
||
| 32 | |||
| 33 | /** @var Array */ |
||
| 34 | protected $cacheTimes = []; // (key => prop => UNIX timestamp) |
||
| 35 | |||
| 36 | protected $maxCacheKeys; // integer; max entries |
||
| 37 | |||
| 38 | /** |
||
| 39 | * @param int $maxKeys Maximum number of entries allowed (min 1). |
||
| 40 | * @throws UnexpectedValueException When $maxCacheKeys is not an int or =< 0. |
||
| 41 | */ |
||
| 42 | public function __construct( $maxKeys ) { |
||
| 45 | |||
| 46 | /** |
||
| 47 | * Set a property field for a cache entry. |
||
| 48 | * This will prune the cache if it gets too large based on LRU. |
||
| 49 | * If the item is already set, it will be pushed to the top of the cache. |
||
| 50 | * |
||
| 51 | * @param string $key |
||
| 52 | * @param string $prop |
||
| 53 | * @param mixed $value |
||
| 54 | * @return void |
||
| 55 | */ |
||
| 56 | public function set( $key, $prop, $value ) { |
||
| 68 | |||
| 69 | /** |
||
| 70 | * Check if a property field exists for a cache entry. |
||
| 71 | * |
||
| 72 | * @param string $key |
||
| 73 | * @param string $prop |
||
| 74 | * @param float $maxAge Ignore items older than this many seconds (since 1.21) |
||
| 75 | * @return bool |
||
| 76 | */ |
||
| 77 | public function has( $key, $prop, $maxAge = 0.0 ) { |
||
| 86 | |||
| 87 | /** |
||
| 88 | * Get a property field for a cache entry. |
||
| 89 | * This returns null if the property is not set. |
||
| 90 | * If the item is already set, it will be pushed to the top of the cache. |
||
| 91 | * |
||
| 92 | * @param string $key |
||
| 93 | * @param string $prop |
||
| 94 | * @return mixed |
||
| 95 | */ |
||
| 96 | public function get( $key, $prop ) { |
||
| 103 | |||
| 104 | /** |
||
| 105 | * Clear one or several cache entries, or all cache entries. |
||
| 106 | * |
||
| 107 | * @param string|array $keys |
||
| 108 | * @return void |
||
| 109 | */ |
||
| 110 | public function clear( $keys = null ) { |
||
| 121 | |||
| 122 | /** |
||
| 123 | * Resize the maximum number of cache entries, removing older entries as needed |
||
| 124 | * |
||
| 125 | * @param int $maxKeys |
||
| 126 | * @return void |
||
| 127 | * @throws UnexpectedValueException |
||
| 128 | */ |
||
| 129 | public function resize( $maxKeys ) { |
||
| 141 | |||
| 142 | /** |
||
| 143 | * Push an entry to the top of the cache |
||
| 144 | * |
||
| 145 | * @param string $key |
||
| 146 | */ |
||
| 147 | protected function ping( $key ) { |
||
| 152 | |||
| 153 | /** |
||
| 154 | * Get cache size |
||
| 155 | * @return int |
||
| 156 | */ |
||
| 157 | public function getSize() { |
||
| 160 | } |
||
| 161 |