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:
Complex classes like autoptimizeCache often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use autoptimizeCache, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
10 | class autoptimizeCache |
||
11 | { |
||
12 | /** |
||
13 | * Cache filename. |
||
14 | * |
||
15 | * @var string |
||
16 | */ |
||
17 | private $filename; |
||
18 | |||
19 | /** |
||
20 | * Cache directory path (with a trailing slash). |
||
21 | * |
||
22 | * @var string |
||
23 | */ |
||
24 | private $cachedir; |
||
25 | |||
26 | /** |
||
27 | * Whether gzipping is done by the web server or us. |
||
28 | * True => we don't gzip, the web server does it. |
||
29 | * False => we do it ourselves. |
||
30 | * |
||
31 | * @var bool |
||
32 | */ |
||
33 | private $nogzip; |
||
34 | |||
35 | /** |
||
36 | * Ctor. |
||
37 | * |
||
38 | * @param string $md5 Hash. |
||
39 | * @param string $ext Extension. |
||
40 | */ |
||
41 | public function __construct( $md5, $ext = 'php' ) |
||
55 | |||
56 | /** |
||
57 | * Returns true if the cached file exists on disk. |
||
58 | * |
||
59 | * @return bool |
||
60 | */ |
||
61 | public function check() |
||
65 | |||
66 | /** |
||
67 | * Returns cache contents if they exist, false otherwise. |
||
68 | * |
||
69 | * @return string|false |
||
70 | */ |
||
71 | public function retrieve() |
||
82 | |||
83 | /** |
||
84 | * Stores given $data in cache. |
||
85 | * |
||
86 | * @param string $data Data to cache. |
||
87 | * @param string $mime Mimetype. |
||
88 | * |
||
89 | * @return void |
||
90 | */ |
||
91 | public function cache( $data, $mime ) |
||
92 | { |
||
93 | // off by default; check if cachedirs exist every time before caching |
||
94 | // |
||
95 | // to be activated for users that experience these ugly errors; |
||
96 | // PHP Warning: file_put_contents failed to open stream: No such file or directory. |
||
97 | if ( apply_filters( 'autoptimize_filter_cache_checkdirs_on_write', false ) ) { |
||
98 | $this->check_and_create_dirs(); |
||
99 | } |
||
100 | |||
101 | if ( false === $this->nogzip ) { |
||
102 | // We handle gzipping ourselves. |
||
103 | $file = 'default.php'; |
||
104 | $phpcode = file_get_contents( AUTOPTIMIZE_PLUGIN_DIR . 'config/' . $file ); |
||
105 | $phpcode = str_replace( array( '%%CONTENT%%', 'exit;' ), array( $mime, '' ), $phpcode ); |
||
106 | |||
107 | file_put_contents( $this->cachedir . $this->filename, $phpcode ); |
||
108 | file_put_contents( $this->cachedir . $this->filename . '.none', $data ); |
||
109 | } else { |
||
110 | // Write code to cache without doing anything else. |
||
111 | file_put_contents( $this->cachedir . $this->filename, $data ); |
||
112 | |||
113 | // save fallback .js or .css file if filter true (to be false by default) but not if snippet or single. |
||
114 | if ( self::do_fallback() && strpos( $this->filename, '_snippet_' ) === false && strpos( $this->filename, '_single_' ) === false ) { |
||
115 | $_extension = pathinfo( $this->filename, PATHINFO_EXTENSION ); |
||
116 | $_fallback_file = AUTOPTIMIZE_CACHEFILE_PREFIX . 'fallback.' . $_extension; |
||
117 | if ( ! file_exists( $this->cachedir . $_extension . '/' . $_fallback_file ) ) { |
||
118 | file_put_contents( $this->cachedir . $_extension . '/' . $_fallback_file, $data ); |
||
119 | } |
||
120 | } |
||
121 | |||
122 | if ( apply_filters( 'autoptimize_filter_cache_create_static_gzip', false ) ) { |
||
123 | // Create an additional cached gzip file. |
||
124 | file_put_contents( $this->cachedir . $this->filename . '.gz', gzencode( $data, 9, FORCE_GZIP ) ); |
||
125 | // If PHP Brotli extension is installed, create an additional cached Brotli file. |
||
126 | if ( function_exists( 'brotli_compress' ) ) { |
||
127 | file_put_contents( $this->cachedir . $this->filename . '.br', brotli_compress( $data, 11, BROTLI_GENERIC ) ); |
||
128 | } |
||
129 | } |
||
130 | } |
||
131 | } |
||
132 | |||
133 | /** |
||
134 | * Get cache filename. |
||
135 | * |
||
136 | * @return string |
||
137 | */ |
||
138 | public function getname() |
||
139 | { |
||
140 | // NOTE: This could've maybe been a do_action() instead, however, |
||
141 | // that ship has sailed. |
||
142 | // The original idea here was to provide 3rd party code a hook so that |
||
143 | // it can "listen" to all the complete autoptimized-urls that the page |
||
144 | // will emit... Or something to that effect I think? |
||
145 | apply_filters( 'autoptimize_filter_cache_getname', AUTOPTIMIZE_CACHE_URL . $this->filename ); |
||
146 | |||
147 | return $this->filename; |
||
148 | } |
||
149 | |||
150 | /** |
||
151 | * Returns true if given `$file` is considered a valid Autoptimize cache file, |
||
152 | * false otherwise. |
||
153 | * |
||
154 | * @param string $dir Directory name (with a trailing slash). |
||
155 | * @param string $file Filename. |
||
156 | * @return bool |
||
157 | */ |
||
158 | protected static function is_valid_cache_file( $dir, $file ) |
||
159 | { |
||
160 | if ( '.' !== $file && '..' !== $file && |
||
161 | false !== strpos( $file, AUTOPTIMIZE_CACHEFILE_PREFIX ) && |
||
162 | is_file( $dir . $file ) ) { |
||
163 | |||
164 | // It's a valid file! |
||
165 | return true; |
||
166 | } |
||
167 | |||
168 | // Everything else is considered invalid! |
||
169 | return false; |
||
170 | } |
||
171 | |||
172 | /** |
||
173 | * Clears contents of AUTOPTIMIZE_CACHE_DIR. |
||
174 | * |
||
175 | * @return void |
||
176 | */ |
||
177 | protected static function clear_cache_classic() |
||
178 | { |
||
179 | $contents = self::get_cache_contents(); |
||
180 | foreach ( $contents as $name => $files ) { |
||
181 | $dir = rtrim( AUTOPTIMIZE_CACHE_DIR . $name, '/' ) . '/'; |
||
182 | foreach ( $files as $file ) { |
||
183 | if ( self::is_valid_cache_file( $dir, $file ) ) { |
||
184 | @unlink( $dir . $file ); // @codingStandardsIgnoreLine |
||
185 | } |
||
186 | } |
||
187 | } |
||
188 | |||
189 | @unlink( AUTOPTIMIZE_CACHE_DIR . '/.htaccess' ); // @codingStandardsIgnoreLine |
||
190 | } |
||
191 | |||
192 | /** |
||
193 | * Recursively deletes the specified pathname (file/directory) if possible. |
||
194 | * Returns true on success, false otherwise. |
||
195 | * |
||
196 | * @param string $pathname Pathname to remove. |
||
197 | * |
||
198 | * @return bool |
||
199 | */ |
||
200 | protected static function rmdir( $pathname ) |
||
201 | { |
||
202 | $files = self::get_dir_contents( $pathname ); |
||
203 | foreach ( $files as $file ) { |
||
204 | $path = $pathname . '/' . $file; |
||
205 | if ( is_dir( $path ) ) { |
||
206 | self::rmdir( $path ); |
||
207 | } else { |
||
208 | unlink( $path ); |
||
209 | } |
||
210 | } |
||
211 | |||
212 | return rmdir( $pathname ); |
||
213 | } |
||
214 | |||
215 | /** |
||
216 | * Clears contents of AUTOPTIMIZE_CACHE_DIR by renaming the current |
||
217 | * cache directory into a new one with a unique name and then |
||
218 | * re-creating the default (empty) cache directory. |
||
219 | * |
||
220 | * Important/ Fixme: this does not take multisite into account, so |
||
221 | * if advanced_cache_clear_enabled is true (it is not by default) |
||
222 | * then the content for all subsites is zapped! |
||
223 | * |
||
224 | * @return bool Returns true when everything is done successfully, false otherwise. |
||
225 | */ |
||
226 | protected static function clear_cache_via_rename() |
||
227 | { |
||
228 | $ok = false; |
||
229 | $dir = self::get_pathname_base(); |
||
230 | $new_name = self::get_unique_name(); |
||
231 | |||
232 | // Makes sure the new pathname is on the same level... |
||
233 | $new_pathname = dirname( $dir ) . '/' . $new_name; |
||
234 | $renamed = @rename( $dir, $new_pathname ); // @codingStandardsIgnoreLine |
||
235 | |||
236 | // When renamed, re-create the default cache directory back so it's |
||
237 | // available again... |
||
238 | if ( $renamed ) { |
||
239 | $ok = self::cacheavail(); |
||
240 | } |
||
241 | |||
242 | return $ok; |
||
243 | } |
||
244 | |||
245 | /** |
||
246 | * Returns true when advanced cache clearing is enabled. |
||
247 | * |
||
248 | * @return bool |
||
249 | */ |
||
250 | public static function advanced_cache_clear_enabled() |
||
251 | { |
||
252 | return apply_filters( 'autoptimize_filter_cache_clear_advanced', false ); |
||
253 | } |
||
254 | |||
255 | /** |
||
256 | * Returns a (hopefully) unique new cache folder name for renaming purposes. |
||
257 | * |
||
258 | * @return string |
||
259 | */ |
||
260 | protected static function get_unique_name() |
||
261 | { |
||
262 | $prefix = self::get_advanced_cache_clear_prefix(); |
||
263 | $new_name = uniqid( $prefix, true ); |
||
264 | |||
265 | return $new_name; |
||
266 | } |
||
267 | |||
268 | /** |
||
269 | * Get cache prefix name used in advanced cache clearing mode. |
||
270 | * |
||
271 | * @return string |
||
272 | */ |
||
273 | protected static function get_advanced_cache_clear_prefix() |
||
274 | { |
||
275 | $pathname = self::get_pathname_base(); |
||
276 | $basename = basename( $pathname ); |
||
277 | $prefix = $basename . '-artifact-'; |
||
278 | |||
279 | return $prefix; |
||
280 | } |
||
281 | |||
282 | /** |
||
283 | * Returns an array of file and directory names found within |
||
284 | * the given $pathname without '.' and '..' elements. |
||
285 | * |
||
286 | * @param string $pathname Pathname. |
||
287 | * |
||
288 | * @return array |
||
289 | */ |
||
290 | protected static function get_dir_contents( $pathname ) |
||
291 | { |
||
292 | return array_slice( scandir( $pathname ), 2 ); |
||
293 | } |
||
294 | |||
295 | /** |
||
296 | * Wipes directories which were created as part of the fast cache clearing |
||
297 | * routine (which renames the current cache directory into a new one with |
||
298 | * a custom-prefixed unique name). |
||
299 | * |
||
300 | * @return bool |
||
301 | */ |
||
302 | public static function delete_advanced_cache_clear_artifacts() |
||
303 | { |
||
304 | // Don't go through these motions (called from the cachechecker) if advanced cache clear isn't even active. |
||
305 | if ( ! self::advanced_cache_clear_enabled() ) { |
||
306 | return false; |
||
307 | } |
||
308 | |||
309 | $dir = self::get_pathname_base(); |
||
310 | $prefix = self::get_advanced_cache_clear_prefix(); |
||
311 | $parent = dirname( $dir ); |
||
312 | $ok = false; |
||
313 | |||
314 | // Returns the list of files without '.' and '..' elements. |
||
315 | $files = self::get_dir_contents( $parent ); |
||
316 | if ( is_array( $files ) && ! empty( $files ) ) { |
||
317 | foreach ( $files as $file ) { |
||
318 | $path = $parent . '/' . $file; |
||
319 | $prefixed = ( false !== strpos( $path, $prefix ) ); |
||
320 | // Removing only our own (prefixed) directories... |
||
321 | if ( is_dir( $path ) && $prefixed ) { |
||
322 | $ok = self::rmdir( $path ); |
||
323 | } |
||
324 | } |
||
325 | } |
||
326 | |||
327 | return $ok; |
||
328 | } |
||
329 | |||
330 | /** |
||
331 | * Returns the cache directory pathname used. |
||
332 | * Done as a function so we canSlightly different |
||
333 | * if multisite is used and `autoptimize_separate_blog_caches` filter |
||
334 | * is used. |
||
335 | * |
||
336 | * @return string |
||
337 | */ |
||
338 | public static function get_pathname() |
||
339 | { |
||
340 | $pathname = self::get_pathname_base(); |
||
341 | |||
342 | View Code Duplication | if ( is_multisite() && apply_filters( 'autoptimize_separate_blog_caches', true ) ) { |
|
343 | $blog_id = get_current_blog_id(); |
||
344 | $pathname .= $blog_id . '/'; |
||
345 | } |
||
346 | |||
347 | return $pathname; |
||
348 | } |
||
349 | |||
350 | /** |
||
351 | * Returns the base path of our cache directory. |
||
352 | * |
||
353 | * @return string |
||
354 | */ |
||
355 | protected static function get_pathname_base() |
||
356 | { |
||
357 | $pathname = WP_CONTENT_DIR . AUTOPTIMIZE_CACHE_CHILD_DIR; |
||
358 | |||
359 | return $pathname; |
||
360 | } |
||
361 | |||
362 | /** |
||
363 | * Deletes everything from the cache directories. |
||
364 | * |
||
365 | * @param bool $propagate Whether to trigger additional actions when cache is purged. |
||
366 | * |
||
367 | * @return bool |
||
368 | */ |
||
369 | public static function clearall( $propagate = true ) |
||
370 | { |
||
371 | if ( ! self::cacheavail() ) { |
||
372 | return false; |
||
373 | } |
||
374 | |||
375 | // TODO/FIXME: If cache is big, switch to advanced/new cache clearing automatically? |
||
376 | if ( self::advanced_cache_clear_enabled() ) { |
||
377 | self::clear_cache_via_rename(); |
||
378 | } else { |
||
379 | self::clear_cache_classic(); |
||
380 | } |
||
381 | |||
382 | // Remove 404 handler if required. |
||
383 | if ( self::do_fallback() ) { |
||
384 | $_fallback_php = trailingslashit( WP_CONTENT_DIR ) . 'autoptimize_404_handler.php'; |
||
385 | @unlink( $_fallback_php ); // @codingStandardsIgnoreLine |
||
386 | } |
||
387 | |||
388 | // Remove the transient so it gets regenerated... |
||
389 | delete_transient( 'autoptimize_stats' ); |
||
390 | |||
391 | // Cache was just purged, clear page cache and allow others to hook into our purging... |
||
392 | if ( true === $propagate ) { |
||
393 | if ( ! function_exists( 'autoptimize_do_cachepurged_action' ) ) { |
||
394 | function autoptimize_do_cachepurged_action() { |
||
397 | } |
||
398 | add_action( 'shutdown', 'autoptimize_do_cachepurged_action', 11 ); |
||
399 | add_action( 'autoptimize_action_cachepurged', array( 'autoptimizeCache', 'flushPageCache' ), 10, 0 ); |
||
400 | } |
||
401 | |||
402 | // Warm cache (part of speedupper)! |
||
403 | if ( apply_filters( 'autoptimize_filter_speedupper', true ) && false == get_transient( 'autoptimize_cache_warmer_protector' ) ) { |
||
404 | set_transient( 'autoptimize_cache_warmer_protector', 'I shall not warm cache for another 10 minutes.', 60 * 10 ); |
||
405 | $url = site_url() . '/?ao_speedup_cachebuster=' . rand( 1, 100000 ); |
||
406 | $url = apply_filters( 'autoptimize_filter_cache_warmer_url', $url ); |
||
407 | $cache = @wp_remote_get( $url ); // @codingStandardsIgnoreLine |
||
408 | unset( $cache ); |
||
409 | } |
||
410 | |||
413 | |||
414 | /** |
||
415 | * Wrapper for clearall but with false param |
||
416 | * to ensure the event is not propagated to others |
||
417 | * through our own hooks (to avoid infinite loops). |
||
418 | * |
||
419 | * @return bool |
||
420 | */ |
||
421 | public static function clearall_actionless() |
||
425 | |||
426 | /** |
||
427 | * Returns the contents of our cache dirs. |
||
428 | * |
||
429 | * @return array |
||
430 | */ |
||
431 | protected static function get_cache_contents() |
||
441 | |||
442 | /** |
||
443 | * Returns stats about cached contents. |
||
444 | * |
||
445 | * @return array |
||
446 | */ |
||
447 | public static function stats() |
||
470 | |||
471 | /** |
||
472 | * Performs a scan of cache directory contents and returns an array |
||
473 | * with 3 values: count, size, timestamp. |
||
474 | * count = total number of found files |
||
475 | * size = total filesize (in bytes) of found files |
||
476 | * timestamp = unix timestamp when the scan was last performed/finished. |
||
477 | * |
||
478 | * @return array |
||
479 | */ |
||
480 | protected static function stats_scan() |
||
513 | |||
514 | /** |
||
515 | * Ensures the cache directory exists, is writeable and contains the |
||
516 | * required .htaccess files. |
||
517 | * Returns false in case it fails to ensure any of those things. |
||
518 | * |
||
519 | * @return bool |
||
520 | */ |
||
521 | public static function cacheavail() |
||
605 | |||
606 | /** |
||
607 | * Checks if fallback-php file exists and create it if not. |
||
608 | * |
||
609 | * Return bool |
||
610 | */ |
||
611 | public static function check_fallback_php() { |
||
628 | |||
629 | /** |
||
630 | * Tells if AO should try to avoid 404's by creating fallback filesize |
||
631 | * and create a php 404 handler and tell .htaccess to redirect to said handler. |
||
632 | * |
||
633 | * Return bool |
||
634 | */ |
||
635 | public static function do_fallback() { |
||
638 | |||
639 | /** |
||
640 | * Checks if cache dirs exist and create if not. |
||
641 | * Returns false if not succesful. |
||
642 | * |
||
643 | * @return bool |
||
644 | */ |
||
645 | public static function check_and_create_dirs() { |
||
658 | |||
659 | /** |
||
660 | * Ensures the specified `$dir` exists and is writeable. |
||
661 | * Returns false if that's not the case. |
||
662 | * |
||
663 | * @param string $dir Directory to check/create. |
||
664 | * |
||
665 | * @return bool |
||
666 | */ |
||
667 | protected static function check_cache_dir( $dir ) |
||
690 | |||
691 | /** |
||
692 | * Flushes as many page cache plugin's caches as possible. |
||
693 | * |
||
694 | * @return void |
||
695 | */ |
||
696 | // @codingStandardsIgnoreStart |
||
697 | public static function flushPageCache() |
||
766 | // @codingStandardsIgnoreEnd |
||
767 | } |
||
768 |
When comparing two booleans, it is generally considered safer to use the strict comparison operator.