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