Conditions | 13 |
Paths | 45 |
Total Lines | 48 |
Code Lines | 29 |
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 |
||
58 | function make(string $imagePath, int $width, int $height = null): string |
||
|
|||
59 | { |
||
60 | if (!file_exists($imagePath)) { |
||
61 | throw new \Exception("Image not found"); |
||
62 | } |
||
63 | |||
64 | $this->imagePath = $imagePath; |
||
65 | $this->imageMime = mime_content_type($this->imagePath); |
||
66 | $this->imageInfo = pathinfo($this->imagePath); |
||
67 | $this->imageName = md5($this->imageInfo['basename']) . "x{$width}{$height}" . ($this->imageMime == "image/jpeg" ? ".jpg" : ".png"); |
||
68 | |||
69 | if (!in_array($this->imageMime, self::$allowedExt)) { |
||
70 | throw new \Exception("Not a valid JPG or PNG image"); |
||
71 | } |
||
72 | |||
73 | if (!file_exists($this->cachePath) || !is_dir($this->cachePath)) { |
||
74 | if (!mkdir($this->cachePath, 0755)) { |
||
75 | throw new \Exception("Could not create cache folder"); |
||
76 | } |
||
77 | } |
||
78 | |||
79 | if (file_exists("{$this->cachePath}/{$this->imageName}") && is_file("{$this->cachePath}/{$this->imageName}")) { |
||
80 | return "{$this->cachePath}/{$this->imageName}"; |
||
81 | } |
||
82 | |||
83 | list($src_w, $src_h) = getimagesize($this->imagePath); |
||
84 | $height = ($height ?? ($width * $src_h) / $src_w); |
||
85 | |||
86 | $src_x = 0; |
||
87 | $src_y = 0; |
||
88 | |||
89 | $cmp_x = $src_w / $width; |
||
90 | $cmp_y = $src_h / $height; |
||
91 | |||
92 | if ($cmp_x > $cmp_y) { |
||
93 | $src_w = round($src_w / $cmp_x * $cmp_y); |
||
94 | $src_x = round(($src_w - ($src_w / $cmp_x * $cmp_y))); //2 |
||
95 | } elseif ($cmp_y > $cmp_x) { |
||
96 | $src_h = round($src_h / $cmp_y * $cmp_x); |
||
97 | $src_y = round(($src_h - ($src_h / $cmp_y * $cmp_x))); //2 |
||
98 | } |
||
99 | |||
100 | if ($this->imageMime == "image/jpeg") { |
||
101 | return $this->fromJpg($width, $height, $src_x, $src_y, $src_w, $src_h); |
||
102 | } |
||
103 | |||
104 | if ($this->imageMime == "image/png") { |
||
105 | return $this->fromPng($width, $height, $src_x, $src_y, $src_w, $src_h); |
||
106 | } |
||
180 | } |
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.