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 TimberImageHelper 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 TimberImageHelper, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
16 | class TimberImageHelper { |
||
17 | |||
18 | const BASE_UPLOADS = 1; |
||
19 | const BASE_CONTENT = 2; |
||
20 | |||
21 | public static function init() { |
||
22 | self::add_constants(); |
||
23 | self::add_actions(); |
||
24 | self::add_filters(); |
||
25 | } |
||
26 | |||
27 | /** |
||
28 | * Generates a new image with the specified dimensions. |
||
29 | * New dimensions are achieved by cropping to maintain ratio. |
||
30 | * |
||
31 | * @api |
||
32 | * @param string $src an URL (absolute or relative) to the original image |
||
33 | * @param int|string $w target width(int) or WordPress image size (WP-set or user-defined). |
||
34 | * @param int $h target height (ignored if $w is WP image size). If not set, will ignore and resize based on $w only. |
||
35 | * @param string $crop your choices are 'default', 'center', 'top', 'bottom', 'left', 'right' |
||
36 | * @param bool $force |
||
37 | * @example |
||
38 | * ```twig |
||
39 | * <img src="{{ image.src | resize(300, 200, 'top') }}" /> |
||
40 | * ``` |
||
41 | * ```html |
||
42 | * <img src="http://example.org/wp-content/uploads/pic-300x200-c-top.jpg" /> |
||
43 | * ``` |
||
44 | * @return string (ex: ) |
||
45 | */ |
||
46 | public static function resize( $src, $w, $h = 0, $crop = 'default', $force = false ) { |
||
47 | if ( !is_numeric($w) && is_string($w) ) { |
||
48 | if ( $sizes = self::find_wp_dimensions($w) ) { |
||
49 | $w = $sizes['w']; |
||
50 | $h = $sizes['h']; |
||
51 | } else { |
||
52 | return $src; |
||
53 | } |
||
54 | } |
||
55 | $op = new TimberImageOperationResize($w, $h, $crop); |
||
56 | return self::_operate($src, $op, $force); |
||
57 | } |
||
58 | |||
59 | /** |
||
60 | * Find the sizes of an image based on a defined image size |
||
61 | * @param string $size the image size to search for |
||
62 | * can be WordPress-defined ("medium") |
||
63 | * or user-defined ("my-awesome-size") |
||
64 | * @return false|array { |
||
65 | * @type int w |
||
66 | * @type int h |
||
67 | * } |
||
68 | */ |
||
69 | private static function find_wp_dimensions( $size ) { |
||
70 | global $_wp_additional_image_sizes; |
||
71 | if ( isset($_wp_additional_image_sizes[$size]) ) { |
||
72 | $w = $_wp_additional_image_sizes[$size]['width']; |
||
73 | $h = $_wp_additional_image_sizes[$size]['height']; |
||
74 | } else if ( in_array($size, array('thumbnail', 'medium', 'large')) ) { |
||
75 | $w = get_option($size.'_size_w'); |
||
76 | $h = get_option($size.'_size_h'); |
||
77 | } |
||
78 | if ( isset($w) && isset($h) && ($w || $h) ) { |
||
79 | return array('w' => $w, 'h' => $h); |
||
80 | } |
||
81 | return false; |
||
82 | } |
||
83 | |||
84 | /** |
||
85 | * Generates a new image with increased size, for display on Retina screens. |
||
86 | * |
||
87 | * @param string $src |
||
88 | * @param float $multiplier |
||
89 | * @param boolean $force |
||
90 | * |
||
91 | * @return string url to the new image |
||
92 | */ |
||
93 | public static function retina_resize( $src, $multiplier = 2, $force = false ) { |
||
97 | |||
98 | /** |
||
99 | * checks to see if the given file is an aimated gif |
||
100 | * @param string $file local filepath to a file, not a URL |
||
101 | * @return boolean true if it's an animated gif, false if not |
||
102 | */ |
||
103 | public static function is_animated_gif( $file ) { |
||
104 | if ( strpos(strtolower($file), '.gif') == -1 ) { |
||
105 | //doesn't have .gif, bail |
||
106 | return false; |
||
107 | } |
||
108 | //its a gif so test |
||
109 | if( !($fh = @fopen($file, 'rb')) ) { |
||
110 | return false; |
||
111 | } |
||
112 | $count = 0; |
||
113 | //an animated gif contains multiple "frames", with each frame having a |
||
114 | //header made up of: |
||
115 | // * a static 4-byte sequence (\x00\x21\xF9\x04) |
||
116 | // * 4 variable bytes |
||
117 | // * a static 2-byte sequence (\x00\x2C) |
||
118 | |||
119 | // We read through the file til we reach the end of the file, or we've found |
||
120 | // at least 2 frame headers |
||
121 | while(!feof($fh) && $count < 2) { |
||
122 | $chunk = fread($fh, 1024 * 100); //read 100kb at a time |
||
123 | $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00[\x2C\x21]#s', $chunk, $matches); |
||
124 | } |
||
125 | |||
126 | fclose($fh); |
||
127 | return $count > 1; |
||
128 | } |
||
129 | |||
130 | /** |
||
131 | * Generate a new image with the specified dimensions. |
||
132 | * New dimensions are achieved by adding colored bands to maintain ratio. |
||
133 | * |
||
134 | * @param string $src |
||
135 | * @param int $w |
||
136 | * @param int $h |
||
137 | * @param string $color |
||
138 | * @param bool $force |
||
139 | * @return mixed|null|string |
||
140 | */ |
||
141 | public static function letterbox( $src, $w, $h, $color = '#000000', $force = false ) { |
||
145 | |||
146 | /** |
||
147 | * Generates a new image by converting the source GIF or PNG into JPG |
||
148 | * |
||
149 | * @param string $src a url or path to the image (http://example.org/wp-content/uploads/2014/image.jpg) or (/wp-content/uploads/2014/image.jpg) |
||
150 | * @param string $bghex |
||
151 | * @return string |
||
152 | */ |
||
153 | public static function img_to_jpg( $src, $bghex = '#FFFFFF', $force = false ) { |
||
157 | |||
158 | /** |
||
159 | * Deletes all resized versions of an image when the source is deleted |
||
160 | */ |
||
161 | protected static function add_actions() { |
||
173 | |||
174 | /** |
||
175 | * Adds a constant defining the path to the content directory relative to the site |
||
176 | * for example /wp-content or /content |
||
177 | */ |
||
178 | protected static function add_constants() { |
||
184 | |||
185 | /** |
||
186 | * adds a 'relative' key to wp_upload_dir() result. |
||
187 | * It will contain the relative url to upload dir. |
||
188 | * @return void |
||
189 | */ |
||
190 | static function add_filters() { |
||
196 | |||
197 | //-- end of public methods --// |
||
198 | /** |
||
199 | * Deletes the auto-generated files for resize and letterboxing created by Timber |
||
200 | * @param string $local_file ex: /var/www/wp-content/uploads/2015/my-pic.jpg |
||
201 | * or: http://example.org/wp-content/uploads/2015/my-pic.jpg |
||
202 | */ |
||
203 | static function delete_generated_files( $local_file ) { |
||
216 | |||
217 | /** |
||
218 | * Deletes resized versions of the supplied file name. |
||
219 | * So if passed a value like my-pic.jpg, this function will delete my-pic-500x200-c-left.jpg, my-pic-400x400-c-default.jpg, etc. |
||
220 | * |
||
221 | * keeping these here so I know what the hell we're matching |
||
222 | * $match = preg_match("/\/srv\/www\/wordpress-develop\/src\/wp-content\/uploads\/2014\/05\/$filename-[0-9]*x[0-9]*-c-[a-z]*.jpg/", $found_file); |
||
223 | * $match = preg_match("/\/srv\/www\/wordpress-develop\/src\/wp-content\/uploads\/2014\/05\/arch-[0-9]*x[0-9]*-c-[a-z]*.jpg/", $filename); |
||
224 | * |
||
225 | * @param string $filename ex: my-pic |
||
226 | * @param string $ext ex: jpg |
||
227 | * @param string $dir var/www/wp-content/uploads/2015/ |
||
228 | * @param string $search_pattern pattern of files to pluck from |
||
229 | * @param string $match_pattern pattern of files to go forth and delete |
||
230 | */ |
||
231 | protected static function process_delete_generated_files( $filename, $ext, $dir, $search_pattern, $match_pattern = null ) { |
||
242 | |||
243 | |||
244 | /** |
||
245 | * Determines the filepath corresponding to a given URL |
||
246 | * |
||
247 | * @param string $url |
||
248 | * @return string |
||
249 | */ |
||
250 | public static function get_server_location( $url ) { |
||
260 | |||
261 | /** |
||
262 | * Determines the filepath where a given external file will be stored. |
||
263 | * |
||
264 | * @param string $file |
||
265 | * @return string |
||
266 | */ |
||
267 | public static function get_sideloaded_file_loc( $file ) { |
||
280 | |||
281 | /** |
||
282 | * downloads an external image to the server and stores it on the server |
||
283 | * |
||
284 | * @param string $file the URL to the original file |
||
285 | * @return string the URL to the downloaded file |
||
286 | */ |
||
287 | public static function sideload_image( $file ) { |
||
311 | |||
312 | /** |
||
313 | * Takes in an URL and breaks it into components, |
||
314 | * that will then be used in the different steps of image processing. |
||
315 | * The image is expected to be either part of a theme, plugin, or an upload. |
||
316 | * |
||
317 | * @param string $url an URL (absolute or relative) pointing to an image |
||
318 | * @return array an array (see keys in code below) |
||
319 | */ |
||
320 | private static function analyze_url($url) { |
||
321 | $result = array( |
||
322 | 'url' => $url, // the initial url |
||
323 | 'absolute' => TimberURLHelper::is_absolute($url), // is the url absolute or relative (to home_url) |
||
324 | 'base' => 0, // is the image in uploads dir, or in content dir (theme or plugin) |
||
325 | 'subdir' => '', // the path between base (uploads or content) and file |
||
326 | 'filename' => '', // the filename, without extension |
||
327 | 'extension' => '', // the file extension |
||
328 | 'basename' => '', // full file name |
||
329 | ); |
||
330 | $upload_dir = wp_upload_dir(); |
||
331 | $tmp = $url; |
||
332 | if ( 0 === strpos($tmp, ABSPATH) ) { // we've been given a dir, not an url |
||
333 | $result['absolute'] = true; |
||
334 | View Code Duplication | if ( 0 === strpos($tmp, $upload_dir['basedir']) ) { |
|
335 | $result['base']= self::BASE_UPLOADS; // upload based |
||
336 | $tmp = str_replace($upload_dir['basedir'], '', $tmp); |
||
337 | } |
||
338 | View Code Duplication | if ( 0 === strpos($tmp, WP_CONTENT_DIR) ) { |
|
339 | $result['base']= self::BASE_CONTENT; // content based |
||
340 | $tmp = str_replace(WP_CONTENT_DIR, '', $tmp); |
||
341 | } |
||
342 | } else { |
||
343 | if (!$result['absolute']) { |
||
344 | $tmp = home_url().$tmp; |
||
345 | } |
||
346 | View Code Duplication | if (0 === strpos($tmp, $upload_dir['baseurl'])) { |
|
347 | $result['base']= self::BASE_UPLOADS; // upload based |
||
348 | $tmp = str_replace($upload_dir['baseurl'], '', $tmp); |
||
349 | } |
||
350 | View Code Duplication | if (0 === strpos($tmp, content_url())) { |
|
351 | $result['base']= self::BASE_CONTENT; // content-based |
||
352 | $tmp = str_replace(content_url(), '', $tmp); |
||
353 | } |
||
354 | } |
||
355 | $parts = pathinfo($tmp); |
||
356 | $result['subdir'] = ($parts['dirname'] === '/') ? '' : $parts['dirname']; |
||
357 | $result['filename'] = $parts['filename']; |
||
358 | $result['extension'] = $parts['extension']; |
||
359 | $result['basename'] = $parts['basename']; |
||
360 | // todo filename |
||
361 | return $result; |
||
362 | } |
||
363 | |||
364 | /** |
||
365 | * Builds the public URL of a file based on its different components |
||
366 | * |
||
367 | * @param int $base one of self::BASE_UPLOADS, self::BASE_CONTENT to indicate if file is an upload or a content (theme or plugin) |
||
368 | * @param string $subdir subdirectory in which file is stored, relative to $base root folder |
||
369 | * @param string $filename file name, including extension (but no path) |
||
370 | * @param bool $absolute should the returned URL be absolute (include protocol+host), or relative |
||
371 | * @return string the URL |
||
372 | */ |
||
373 | private static function _get_file_url($base, $subdir, $filename, $absolute) { |
||
392 | |||
393 | /** |
||
394 | * Builds the absolute file system location of a file based on its different components |
||
395 | * |
||
396 | * @param int $base one of self::BASE_UPLOADS, self::BASE_CONTENT to indicate if file is an upload or a content (theme or plugin) |
||
397 | * @param string $subdir subdirectory in which file is stored, relative to $base root folder |
||
398 | * @param string $filename file name, including extension (but no path) |
||
399 | * @return string the file location |
||
400 | */ |
||
401 | private static function _get_file_path($base, $subdir, $filename) { |
||
416 | |||
417 | |||
418 | /** |
||
419 | * Main method that applies operation to src image: |
||
420 | * 1. break down supplied URL into components |
||
421 | * 2. use components to determine result file and URL |
||
422 | * 3. check if a result file already exists |
||
423 | * 4. otherwise, delegate to supplied TimberImageOperation |
||
424 | * |
||
425 | * @param string $src an URL (absolute or relative) to an image |
||
426 | * @param object $op object of class TimberImageOperation |
||
427 | * @param boolean $force if true, remove any already existing result file and forces file generation |
||
428 | * @return string URL to the new image - or the source one if error |
||
429 | * |
||
430 | */ |
||
431 | private static function _operate( $src, $op, $force = false ) { |
||
482 | |||
483 | |||
484 | // -- the below methods are just used for unit testing the URL generation code |
||
485 | // |
||
486 | View Code Duplication | static function get_letterbox_file_url($url, $w, $h, $color) { |
|
528 | |||
529 | |||
530 | } |
||
531 |
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.