| Conditions | 6 |
| Paths | 4 |
| Total Lines | 54 |
| 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 |
||
| 72 | public function cleanup() { |
||
| 73 | |||
| 74 | // Get all the files, recursive. |
||
| 75 | $files = $this->reduce( array(), Ttl_Cache::get_cache_folder() ); |
||
| 76 | |||
| 77 | |||
| 78 | // Get the max mtime. |
||
| 79 | $max_mtime = time() - WORDLIFT_CACHE_DEFAULT_TTL; |
||
| 80 | |||
| 81 | // Keep the original count for statistics that we're going to send the client. |
||
| 82 | $original_count = count( $files ); |
||
| 83 | |||
| 84 | // Sort by size ascending. |
||
| 85 | usort( $files, function ( $f1, $f2 ) { |
||
| 86 | if ( $f1[ Ttl_Cache_Cleaner::MTIME ] === $f2[ Ttl_Cache_Cleaner::MTIME ] ) { |
||
| 87 | return 0; |
||
| 88 | } |
||
| 89 | |||
| 90 | return ( $f1[ Ttl_Cache_Cleaner::MTIME ] < $f2[ Ttl_Cache_Cleaner::MTIME ] ) ? - 1 : 1; |
||
| 91 | } ); |
||
| 92 | |||
| 93 | // Start removing stale files. |
||
| 94 | for ( $i = 0; $i < count( $files ); $i ++ ) { |
||
|
|
|||
| 95 | $file = $files[ $i ]; |
||
| 96 | // Break if the mtime is within the range. |
||
| 97 | if ( $file[ Ttl_Cache_Cleaner::MTIME ] > $max_mtime ) { |
||
| 98 | break; |
||
| 99 | } |
||
| 100 | |||
| 101 | unset( $files[ $i ] ); |
||
| 102 | @unlink( $file[ Ttl_Cache_Cleaner::PATH ] ); |
||
| 103 | } |
||
| 104 | |||
| 105 | // Calculate the size. |
||
| 106 | $total_size = array_reduce( $files, function ( $carry, $item ) { |
||
| 107 | |||
| 108 | return $carry + $item[ Ttl_Cache_Cleaner::SIZE ]; |
||
| 109 | }, 0 ); |
||
| 110 | |||
| 111 | |||
| 112 | // Remove files until we're within the max size. |
||
| 113 | while ( $total_size > $this->max_size ) { |
||
| 114 | $file = array_shift( $files ); |
||
| 115 | $total_size -= $file[ Ttl_Cache_Cleaner::SIZE ]; |
||
| 116 | @unlink( $file[ Ttl_Cache_Cleaner::PATH ] ); |
||
| 117 | } |
||
| 118 | |||
| 119 | // Send back some stats. |
||
| 120 | wp_send_json_success( array( |
||
| 121 | 'initial_count' => $original_count, |
||
| 122 | 'current_count' => count( $files ), |
||
| 123 | 'current_size' => $total_size, |
||
| 124 | ) ); |
||
| 125 | } |
||
| 126 | |||
| 183 |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: