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' ) |
||
60 | |||
61 | /** |
||
62 | * Returns true if the cached file exists on disk. |
||
63 | * |
||
64 | * @return bool |
||
65 | */ |
||
66 | public function check() |
||
70 | |||
71 | /** |
||
72 | * Returns cache contents if they exist, false otherwise. |
||
73 | * |
||
74 | * @return string|false |
||
75 | */ |
||
76 | public function retrieve() |
||
87 | |||
88 | /** |
||
89 | * Stores given $data in cache. |
||
90 | * |
||
91 | * @param string $data Data to cache. |
||
92 | * @param string $mime Mimetype. |
||
93 | * |
||
94 | * @return void |
||
95 | */ |
||
96 | public function cache( $data, $mime ) |
||
97 | { |
||
98 | // readonly FS explicitly OK'ed by developer, so just pretend all is OK. |
||
99 | if ( defined( 'AUTOPTIMIZE_CACHE_READONLY' ) ) { |
||
100 | return true; |
||
101 | } |
||
102 | |||
103 | // off by default; check if cachedirs exist every time before caching |
||
104 | // |
||
105 | // to be activated for users that experience these ugly errors; |
||
106 | // PHP Warning: file_put_contents failed to open stream: No such file or directory. |
||
107 | if ( apply_filters( 'autoptimize_filter_cache_checkdirs_on_write', false ) ) { |
||
108 | $this->check_and_create_dirs(); |
||
109 | } |
||
110 | |||
111 | if ( false === $this->nogzip ) { |
||
112 | // We handle gzipping ourselves. |
||
113 | $file = 'default.php'; |
||
114 | $phpcode = file_get_contents( AUTOPTIMIZE_PLUGIN_DIR . 'config/' . $file ); |
||
115 | $phpcode = str_replace( array( '%%CONTENT%%', 'exit;' ), array( $mime, '' ), $phpcode ); |
||
116 | |||
117 | file_put_contents( $this->cachedir . $this->filename, $phpcode ); |
||
118 | file_put_contents( $this->cachedir . $this->filename . '.none', $data ); |
||
119 | } else { |
||
120 | // Write code to cache without doing anything else. |
||
121 | file_put_contents( $this->cachedir . $this->filename, $data ); |
||
122 | |||
123 | // save fallback .js or .css file if filter true (to be false by default) but not if snippet or single. |
||
124 | if ( self::do_fallback() && strpos( $this->filename, '_snippet_' ) === false && strpos( $this->filename, '_single_' ) === false ) { |
||
125 | $_extension = pathinfo( $this->filename, PATHINFO_EXTENSION ); |
||
126 | $_fallback_file = AUTOPTIMIZE_CACHEFILE_PREFIX . 'fallback.' . $_extension; |
||
127 | if ( ( 'css' === $_extension || 'js' === $_extension ) && ! file_exists( $this->cachedir . $_extension . '/' . $_fallback_file ) ) { |
||
128 | file_put_contents( $this->cachedir . $_extension . '/' . $_fallback_file, $data ); |
||
129 | } |
||
130 | } |
||
131 | |||
132 | if ( apply_filters( 'autoptimize_filter_cache_create_static_gzip', false ) ) { |
||
133 | // Create an additional cached gzip file. |
||
134 | file_put_contents( $this->cachedir . $this->filename . '.gz', gzencode( $data, 9, FORCE_GZIP ) ); |
||
135 | // If PHP Brotli extension is installed, create an additional cached Brotli file. |
||
136 | if ( function_exists( 'brotli_compress' ) ) { |
||
137 | file_put_contents( $this->cachedir . $this->filename . '.br', brotli_compress( $data, 11, BROTLI_GENERIC ) ); |
||
138 | } |
||
139 | } |
||
140 | } |
||
141 | |||
142 | // Provide 3rd party action hook for every cache file that is created. |
||
143 | // This hook can for example be used to inject a copy of the created cache file to a other domain. |
||
144 | do_action( 'autoptimize_action_cache_file_created', $this->cachedir . $this->filename ); |
||
145 | } |
||
146 | |||
147 | /** |
||
148 | * Get cache filename. |
||
149 | * |
||
150 | * @return string |
||
151 | */ |
||
152 | public function getname() |
||
153 | { |
||
154 | // NOTE: This could've maybe been a do_action() instead, however, |
||
155 | // that ship has sailed. |
||
156 | // The original idea here was to provide 3rd party code a hook so that |
||
157 | // it can "listen" to all the complete autoptimized-urls that the page |
||
158 | // will emit... Or something to that effect I think? |
||
159 | apply_filters( 'autoptimize_filter_cache_getname', AUTOPTIMIZE_CACHE_URL . $this->filename ); |
||
160 | |||
161 | return $this->filename; |
||
162 | } |
||
163 | |||
164 | /** |
||
165 | * Returns true if given `$file` is considered a valid Autoptimize cache file, |
||
166 | * false otherwise. |
||
167 | * |
||
168 | * @param string $dir Directory name (with a trailing slash). |
||
169 | * @param string $file Filename. |
||
170 | * @return bool |
||
171 | */ |
||
172 | protected static function is_valid_cache_file( $dir, $file ) |
||
173 | { |
||
174 | if ( '.' !== $file && '..' !== $file && |
||
175 | false !== strpos( $file, AUTOPTIMIZE_CACHEFILE_PREFIX ) && |
||
176 | is_file( $dir . $file ) ) { |
||
177 | |||
178 | // It's a valid file! |
||
179 | return true; |
||
180 | } |
||
181 | |||
182 | // Everything else is considered invalid! |
||
183 | return false; |
||
184 | } |
||
185 | |||
186 | /** |
||
187 | * Clears contents of AUTOPTIMIZE_CACHE_DIR. |
||
188 | * |
||
189 | * @return void |
||
190 | */ |
||
191 | protected static function clear_cache_classic() |
||
192 | { |
||
193 | $contents = self::get_cache_contents(); |
||
194 | foreach ( $contents as $name => $files ) { |
||
195 | $dir = rtrim( AUTOPTIMIZE_CACHE_DIR . $name, '/' ) . '/'; |
||
196 | foreach ( $files as $file ) { |
||
197 | if ( self::is_valid_cache_file( $dir, $file ) ) { |
||
198 | @unlink( $dir . $file ); // @codingStandardsIgnoreLine |
||
199 | } |
||
200 | } |
||
201 | } |
||
202 | |||
203 | @unlink( AUTOPTIMIZE_CACHE_DIR . '/.htaccess' ); // @codingStandardsIgnoreLine |
||
204 | } |
||
205 | |||
206 | /** |
||
207 | * Recursively deletes the specified pathname (file/directory) if possible. |
||
208 | * Returns true on success, false otherwise. |
||
209 | * |
||
210 | * @param string $pathname Pathname to remove. |
||
211 | * |
||
212 | * @return bool |
||
213 | */ |
||
214 | protected static function rmdir( $pathname ) |
||
215 | { |
||
216 | $files = self::get_dir_contents( $pathname ); |
||
217 | foreach ( $files as $file ) { |
||
218 | $path = $pathname . '/' . $file; |
||
219 | if ( is_dir( $path ) ) { |
||
220 | self::rmdir( $path ); |
||
221 | } else { |
||
222 | unlink( $path ); |
||
223 | } |
||
224 | } |
||
225 | |||
226 | return rmdir( $pathname ); |
||
227 | } |
||
228 | |||
229 | /** |
||
230 | * Clears contents of AUTOPTIMIZE_CACHE_DIR by renaming the current |
||
231 | * cache directory into a new one with a unique name and then |
||
232 | * re-creating the default (empty) cache directory. |
||
233 | * |
||
234 | * Important/ Fixme: this does not take multisite into account, so |
||
235 | * if advanced_cache_clear_enabled is true (it is not by default) |
||
236 | * then the content for all subsites is zapped! |
||
237 | * |
||
238 | * @return bool Returns true when everything is done successfully, false otherwise. |
||
239 | */ |
||
240 | protected static function clear_cache_via_rename() |
||
241 | { |
||
242 | $ok = false; |
||
243 | $dir = self::get_pathname_base(); |
||
244 | $new_name = self::get_unique_name(); |
||
245 | |||
246 | // Makes sure the new pathname is on the same level... |
||
247 | $new_pathname = dirname( $dir ) . '/' . $new_name; |
||
248 | $renamed = @rename( $dir, $new_pathname ); // @codingStandardsIgnoreLine |
||
249 | |||
250 | // When renamed, re-create the default cache directory back so it's |
||
251 | // available again... |
||
252 | if ( $renamed ) { |
||
253 | $ok = self::cacheavail(); |
||
254 | } |
||
255 | |||
256 | return $ok; |
||
257 | } |
||
258 | |||
259 | /** |
||
260 | * Returns true when advanced cache clearing is enabled. |
||
261 | * |
||
262 | * @return bool |
||
263 | */ |
||
264 | public static function advanced_cache_clear_enabled() |
||
265 | { |
||
266 | return apply_filters( 'autoptimize_filter_cache_clear_advanced', false ); |
||
267 | } |
||
268 | |||
269 | /** |
||
270 | * Returns a (hopefully) unique new cache folder name for renaming purposes. |
||
271 | * |
||
272 | * @return string |
||
273 | */ |
||
274 | protected static function get_unique_name() |
||
275 | { |
||
276 | $prefix = self::get_advanced_cache_clear_prefix(); |
||
277 | $new_name = uniqid( $prefix, true ); |
||
278 | |||
279 | return $new_name; |
||
280 | } |
||
281 | |||
282 | /** |
||
283 | * Get cache prefix name used in advanced cache clearing mode. |
||
284 | * |
||
285 | * @return string |
||
286 | */ |
||
287 | protected static function get_advanced_cache_clear_prefix() |
||
288 | { |
||
289 | $pathname = self::get_pathname_base(); |
||
290 | $basename = basename( $pathname ); |
||
291 | $prefix = $basename . '-artifact-'; |
||
292 | |||
293 | return $prefix; |
||
294 | } |
||
295 | |||
296 | /** |
||
297 | * Returns an array of file and directory names found within |
||
298 | * the given $pathname without '.' and '..' elements. |
||
299 | * |
||
300 | * @param string $pathname Pathname. |
||
301 | * |
||
302 | * @return array |
||
303 | */ |
||
304 | protected static function get_dir_contents( $pathname ) |
||
305 | { |
||
306 | return array_slice( scandir( $pathname ), 2 ); |
||
307 | } |
||
308 | |||
309 | /** |
||
310 | * Wipes directories which were created as part of the fast cache clearing |
||
311 | * routine (which renames the current cache directory into a new one with |
||
312 | * a custom-prefixed unique name). |
||
313 | * |
||
314 | * @return bool |
||
315 | */ |
||
316 | public static function delete_advanced_cache_clear_artifacts() |
||
317 | { |
||
318 | // Don't go through these motions (called from the cachechecker) if advanced cache clear isn't even active. |
||
319 | if ( ! self::advanced_cache_clear_enabled() ) { |
||
320 | return false; |
||
321 | } |
||
322 | |||
323 | $dir = self::get_pathname_base(); |
||
324 | $prefix = self::get_advanced_cache_clear_prefix(); |
||
325 | $parent = dirname( $dir ); |
||
326 | $ok = false; |
||
327 | |||
328 | // Returns the list of files without '.' and '..' elements. |
||
329 | $files = self::get_dir_contents( $parent ); |
||
330 | if ( is_array( $files ) && ! empty( $files ) ) { |
||
331 | foreach ( $files as $file ) { |
||
332 | $path = $parent . '/' . $file; |
||
333 | $prefixed = ( false !== strpos( $path, $prefix ) ); |
||
334 | // Removing only our own (prefixed) directories... |
||
335 | if ( is_dir( $path ) && $prefixed ) { |
||
336 | $ok = self::rmdir( $path ); |
||
337 | } |
||
338 | } |
||
339 | } |
||
340 | |||
341 | return $ok; |
||
342 | } |
||
343 | |||
344 | /** |
||
345 | * Returns the cache directory pathname used. |
||
346 | * Done as a function so we canSlightly different |
||
347 | * if multisite is used and `autoptimize_separate_blog_caches` filter |
||
348 | * is used. |
||
349 | * |
||
350 | * @return string |
||
351 | */ |
||
352 | public static function get_pathname() |
||
353 | { |
||
354 | $pathname = self::get_pathname_base(); |
||
355 | |||
356 | View Code Duplication | if ( is_multisite() && apply_filters( 'autoptimize_separate_blog_caches', true ) ) { |
|
357 | $blog_id = get_current_blog_id(); |
||
358 | $pathname .= $blog_id . '/'; |
||
359 | } |
||
360 | |||
361 | return $pathname; |
||
362 | } |
||
363 | |||
364 | /** |
||
365 | * Returns the base path of our cache directory. |
||
366 | * |
||
367 | * @return string |
||
368 | */ |
||
369 | protected static function get_pathname_base() |
||
370 | { |
||
371 | $pathname = WP_CONTENT_DIR . AUTOPTIMIZE_CACHE_CHILD_DIR; |
||
372 | |||
373 | return $pathname; |
||
374 | } |
||
375 | |||
376 | /** |
||
377 | * Deletes everything from the cache directories. |
||
378 | * |
||
379 | * @param bool $propagate Whether to trigger additional actions when cache is purged. |
||
380 | * |
||
381 | * @return bool |
||
382 | */ |
||
383 | public static function clearall( $propagate = true ) |
||
384 | { |
||
385 | if ( ! self::cacheavail() ) { |
||
386 | return false; |
||
387 | } |
||
388 | |||
389 | // TODO/FIXME: If cache is big, switch to advanced/new cache clearing automatically? |
||
390 | if ( self::advanced_cache_clear_enabled() ) { |
||
391 | self::clear_cache_via_rename(); |
||
392 | } else { |
||
393 | self::clear_cache_classic(); |
||
394 | } |
||
395 | |||
396 | // Remove 404 handler if required. |
||
397 | if ( self::do_fallback() ) { |
||
398 | $_fallback_php = trailingslashit( WP_CONTENT_DIR ) . 'autoptimize_404_handler.php'; |
||
399 | @unlink( $_fallback_php ); // @codingStandardsIgnoreLine |
||
400 | } |
||
401 | |||
402 | // Remove the transient so it gets regenerated... |
||
403 | delete_transient( 'autoptimize_stats' ); |
||
404 | |||
405 | // Cache was just purged, clear page cache and allow others to hook into our purging... |
||
406 | if ( true === $propagate ) { |
||
407 | if ( ! function_exists( 'autoptimize_do_cachepurged_action' ) ) { |
||
408 | function autoptimize_do_cachepurged_action() { |
||
411 | } |
||
412 | add_action( 'shutdown', 'autoptimize_do_cachepurged_action', 11 ); |
||
413 | add_action( 'autoptimize_action_cachepurged', array( 'autoptimizeCache', 'flushPageCache' ), 10, 0 ); |
||
414 | } |
||
415 | |||
416 | // Warm cache (part of speedupper)! |
||
417 | if ( apply_filters( 'autoptimize_filter_speedupper', true ) && false == get_transient( 'autoptimize_cache_warmer_protector' ) ) { |
||
418 | set_transient( 'autoptimize_cache_warmer_protector', 'I shall not warm cache for another 10 minutes.', 60 * 10 ); |
||
419 | $url = site_url() . '/?ao_speedup_cachebuster=' . rand( 1, 100000 ); |
||
420 | $url = apply_filters( 'autoptimize_filter_cache_warmer_url', $url ); |
||
421 | $cache = @wp_remote_get( $url ); // @codingStandardsIgnoreLine |
||
422 | unset( $cache ); |
||
423 | } |
||
424 | |||
427 | |||
428 | /** |
||
429 | * Wrapper for clearall but with false param |
||
430 | * to ensure the event is not propagated to others |
||
431 | * through our own hooks (to avoid infinite loops). |
||
432 | * |
||
433 | * @return bool |
||
434 | */ |
||
435 | public static function clearall_actionless() |
||
439 | |||
440 | /** |
||
441 | * Returns the contents of our cache dirs. |
||
442 | * |
||
443 | * @return array |
||
444 | */ |
||
445 | protected static function get_cache_contents() |
||
455 | |||
456 | /** |
||
457 | * Returns stats about cached contents. |
||
458 | * |
||
459 | * @return array |
||
460 | */ |
||
461 | public static function stats() |
||
484 | |||
485 | /** |
||
486 | * Performs a scan of cache directory contents and returns an array |
||
487 | * with 3 values: count, size, timestamp. |
||
488 | * count = total number of found files |
||
489 | * size = total filesize (in bytes) of found files |
||
490 | * timestamp = unix timestamp when the scan was last performed/finished. |
||
491 | * |
||
492 | * @return array |
||
493 | */ |
||
494 | protected static function stats_scan() |
||
527 | |||
528 | /** |
||
529 | * Ensures the cache directory exists, is writeable and contains the |
||
530 | * required .htaccess files. |
||
531 | * Returns false in case it fails to ensure any of those things. |
||
532 | * |
||
533 | * @return bool |
||
534 | */ |
||
535 | public static function cacheavail() |
||
624 | |||
625 | /** |
||
626 | * Checks if fallback-php file exists and create it if not. |
||
627 | * |
||
628 | * Return bool |
||
629 | */ |
||
630 | public static function check_fallback_php() { |
||
647 | |||
648 | /** |
||
649 | * Tells if AO should try to avoid 404's by creating fallback filesize |
||
650 | * and create a php 404 handler and tell .htaccess to redirect to said handler |
||
651 | * and hook into WordPress to redirect 404 to said handler as well. NGINX users |
||
652 | * are smart enough to get this working, no? ;-) |
||
653 | * |
||
654 | * Return bool |
||
655 | */ |
||
656 | public static function do_fallback() { |
||
665 | |||
666 | /** |
||
667 | * Hooks into template_redirect, will act on 404-ing requests for |
||
668 | * Autoptimized files and redirects to the fallback CSS/ JS if available |
||
669 | * and 410'ing ("Gone") if fallback not available. |
||
670 | */ |
||
671 | public static function wordpress_notfound_fallback() { |
||
700 | |||
701 | /** |
||
702 | * Checks if cache dirs exist and create if not. |
||
703 | * Returns false if not succesful. |
||
704 | * |
||
705 | * @return bool |
||
706 | */ |
||
707 | public static function check_and_create_dirs() { |
||
720 | |||
721 | /** |
||
722 | * Ensures the specified `$dir` exists and is writeable. |
||
723 | * Returns false if that's not the case. |
||
724 | * |
||
725 | * @param string $dir Directory to check/create. |
||
726 | * |
||
727 | * @return bool |
||
728 | */ |
||
729 | protected static function check_cache_dir( $dir ) |
||
752 | |||
753 | /** |
||
754 | * Flushes as many page cache plugin's caches as possible. |
||
755 | * |
||
756 | * @return void |
||
757 | */ |
||
758 | // @codingStandardsIgnoreStart |
||
759 | public static function flushPageCache() |
||
832 | // @codingStandardsIgnoreEnd |
||
833 | } |
||
834 |
When comparing two booleans, it is generally considered safer to use the strict comparison operator.