Conditions | 8 |
Paths | 13 |
Total Lines | 55 |
Code Lines | 37 |
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 |
||
12 | function crop($image, $mimeType, $imgWidth, $imgHeight, $newWidth, $newHeight){ |
||
13 | |||
14 | switch ($mimeType) { |
||
15 | case "jpg": |
||
16 | case "jpeg": |
||
17 | $imageCreate = imagecreatefromjpeg($image); |
||
18 | break; |
||
19 | |||
20 | case "png": |
||
21 | $imageCreate = imagecreatefrompng($image); |
||
22 | break; |
||
23 | |||
24 | case "gif": |
||
25 | $imageCreate = imagecreatefromgif($image); |
||
26 | break; |
||
27 | |||
28 | default: |
||
29 | throw new \Exception(" Only gif, jpg, jpeg and png files can be cropped "); |
||
30 | break; |
||
31 | } |
||
32 | |||
33 | // The image offsets/coordination to crop the image. |
||
34 | $widthTrim = ceil(($imgWidth - $newWidth) / 2); |
||
35 | $heightTrim = ceil(($imgHeight - $newHeight) / 2); |
||
36 | |||
37 | // Can't crop to a bigger size, ex: |
||
38 | // an image with 100X100 can not be cropped to 200X200. Image can only be cropped to smaller size. |
||
39 | if ($widthTrim < 0 && $heightTrim < 0) { |
||
40 | return ; |
||
41 | } |
||
42 | |||
43 | $temp = imagecreatetruecolor($newWidth, $newHeight); |
||
44 | imageAlphaBlending($temp, false); |
||
45 | imageSaveAlpha($temp, true); |
||
46 | imagecopyresampled( |
||
47 | $temp, |
||
48 | $imageCreate, |
||
49 | 0, |
||
50 | 0, |
||
51 | $widthTrim, |
||
52 | $heightTrim, |
||
53 | $newWidth, |
||
54 | $newHeight, |
||
55 | $newWidth, |
||
56 | $newHeight |
||
57 | ); |
||
58 | |||
59 | |||
60 | if (!$temp) { |
||
61 | throw new \Exception("Failed to crop image. Please pass the right parameters"); |
||
62 | } else { |
||
63 | imagejpeg($temp, $image); |
||
64 | } |
||
65 | |||
66 | } |
||
67 | |||
68 |