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