Conditions | 13 |
Paths | 19 |
Total Lines | 67 |
Code Lines | 41 |
Lines | 0 |
Ratio | 0 % |
Changes | 3 | ||
Bugs | 0 | Features | 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 |
||
33 | public static function generateThumbnail($imageStr, $target, $maxWidth, $maxHeight, $crop = false) |
||
34 | { |
||
35 | if (! touch($target)) { |
||
36 | throw new ImageConvertException('Target file is not writable.'); |
||
37 | } |
||
38 | |||
39 | if ($crop && ($maxWidth == 0 || $maxHeight == 0)) { |
||
40 | throw new ImageConvertException('Both width and height must be provided for cropping'); |
||
41 | } |
||
42 | |||
43 | $sourceImg = static::imageCreateFromString($imageStr); |
||
44 | if ($sourceImg === false) { |
||
45 | throw new NotAnImageException(); |
||
46 | } |
||
47 | |||
48 | $originalWidth = imagesx($sourceImg); |
||
49 | $originalHeight = imagesy($sourceImg); |
||
50 | if ($maxWidth > $originalWidth) { |
||
51 | $maxWidth = $originalWidth; |
||
52 | } |
||
53 | if ($maxHeight > $originalHeight) { |
||
54 | $maxHeight = $originalHeight; |
||
55 | } |
||
56 | |||
57 | list($finalWidth, $finalHeight) = self::calcNewSize( |
||
58 | $originalWidth, |
||
59 | $originalHeight, |
||
60 | $maxWidth, |
||
61 | $maxHeight, |
||
62 | $crop |
||
63 | ); |
||
64 | |||
65 | $targetImg = imagecreatetruecolor($finalWidth, $finalHeight); |
||
66 | if ($targetImg === false) { |
||
67 | throw new ImageConvertException('Could not generate the thumbnail from source image.'); |
||
68 | } |
||
69 | |||
70 | if (! imagecopyresized( |
||
71 | $targetImg, |
||
72 | $sourceImg, |
||
73 | 0, |
||
74 | 0, |
||
75 | 0, |
||
76 | 0, |
||
77 | $finalWidth, |
||
78 | $finalHeight, |
||
79 | $originalWidth, |
||
80 | $originalHeight |
||
81 | ) |
||
82 | ) { |
||
83 | static::imageDestroy($sourceImg); |
||
84 | static::imageDestroy($targetImg); |
||
85 | throw new ImageConvertException('Could not generate the thumbnail from source image.'); |
||
86 | } |
||
87 | |||
88 | if ($crop) { |
||
89 | $targetImg = imagecrop($targetImg, [ |
||
90 | 'x' => $finalWidth >= $finalHeight ? ($finalWidth - $maxWidth) / 2 : 0, |
||
91 | 'y' => $finalHeight <= $finalWidth ? ($finalHeight - $maxHeight) / 2 : 0, |
||
92 | 'width' => $maxWidth, |
||
93 | 'height' => $maxHeight |
||
94 | ]); |
||
95 | } |
||
96 | |||
97 | imagedestroy($sourceImg); |
||
98 | imagejpeg($targetImg, $target); |
||
|
|||
99 | imagedestroy($targetImg); |
||
100 | } |
||
197 |