Conditions | 9 |
Paths | 28 |
Total Lines | 59 |
Code Lines | 29 |
Lines | 0 |
Ratio | 0 % |
Changes | 4 | ||
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 |
||
50 | public function resize(string $path, int $size): string |
||
51 | { |
||
52 | // is not a local image? |
||
53 | if (Util::isExternalUrl($path)) { |
||
54 | $this->local = false; |
||
55 | } |
||
56 | |||
57 | $this->path = '/'.ltrim($path, '/'); |
||
58 | if (!$this->local) { |
||
59 | $this->path = $path; |
||
60 | } |
||
61 | $this->size = $size; |
||
62 | $returnPath = '/'.self::CACHE_IMAGES_THUMBS_DIR.'/'.$this->size.$this->path; |
||
63 | |||
64 | // source file |
||
65 | $this->setSource(); |
||
66 | |||
67 | // images cache path |
||
68 | $this->cachePath = $this->config->getCachePath().'/'.self::CACHE_IMAGES_THUMBS_DIR.'/'; |
||
|
|||
69 | |||
70 | // is size is already OK? |
||
71 | list($width, $height) = getimagesize($this->source); |
||
72 | if ($width <= $this->size && $height <= $this->size) { |
||
73 | return $this->path; |
||
74 | } |
||
75 | |||
76 | // if GD extension is not installed: can't process |
||
77 | if (!extension_loaded('gd')) { |
||
78 | throw new Exception('GD extension is required to use images resize.'); |
||
79 | } |
||
80 | |||
81 | $this->destination = $this->cachePath.$this->size.$this->path; |
||
82 | |||
83 | if (Util::getFS()->exists($this->destination)) { |
||
84 | return $returnPath; |
||
85 | } |
||
86 | |||
87 | // image object |
||
88 | try { |
||
89 | $img = ImageManager::make($this->source); |
||
90 | $img->resize($this->size, null, function (\Intervention\Image\Constraint $constraint) { |
||
91 | $constraint->aspectRatio(); |
||
92 | $constraint->upsize(); |
||
93 | }); |
||
94 | } catch (NotReadableException $e) { |
||
95 | throw new Exception(sprintf('Cannot get image "%s"', $this->path)); |
||
96 | } |
||
97 | |||
98 | // return data:image for external image |
||
99 | if (!$this->local) { |
||
100 | return (string) $img->encode('data-url'); |
||
101 | } |
||
102 | |||
103 | // save file |
||
104 | Util::getFS()->mkdir(dirname($this->destination)); |
||
105 | $img->save($this->destination); |
||
106 | |||
107 | // return new path |
||
108 | return $returnPath; |
||
109 | } |
||
131 |