disk = $disk; $this->uploadDir = $uploadDir; $this->media = $media; } public function generate(string $file): void { $this->source = app(FileObserver::class)->normalizePath($file); if ($this->media->findFiles($this->source)[0]->getFileType() !== 'image') { return; } $this->copyOriginalImage(); $this->generateVersions(); } public function copyOriginalImage() { $this->disk->put($this->destinationFilename(), $this->media->get($this->source)); } private function destinationFilename(): string { return $this->uploadDir.$this->source; } private function dimensions(): Collection { [$width, $height] = getimagesize(Storage::path($this->destinationFilename())); return collect(compact('width', 'height')); } private function sizes(): Collection { $sizes = Setting::get('sizes'); return collect(array_column($sizes, 'aspect_ratio'))->map( fn ($ratio) => collect(array_combine(['width', 'height'], explode('x', $ratio))), ); } private function possibleSizes(): Collection { $return = collect([]); $ratios = collect(); $ratios->push($this->dimensions()); $ratios = $ratios->merge($this->sizes()); foreach (collect(Setting::get('breakpoints'))->push($this->dimensions()->get('width'))->unique() as $size) { foreach ($ratios as $ratio) { $height = $size * $ratio->get('height') / $ratio->get('width'); $return->push(collect([ 'width' => round($size), 'height' => round($height), ])); } } return $return; } private function generateVersions(): void { foreach ($this->possibleSizes() as $size) { $temp = microtime().'.jpg'; $this->disk->copy($this->destinationFilename(), $temp); $fullOriginalPath = $this->disk->path($this->destinationFilename()); $pathinfo = collect(pathinfo($this->destinationFilename())); $r = app(ImageManager::class)->make($this->disk->path($temp)) ->fit($size->get('width'), $size->get('height'), fn ($constraint) => $constraint->upsize()) ->save($this->disk->path($temp)); list($destWidth, $destHeight) = getimagesize($this->disk->path($temp)); $versionFilename = $pathinfo->get('dirname'). '/'. $pathinfo->get('filename'). '-'. $destWidth. 'x'. $destHeight. '.'. $pathinfo->get('extension'); if ($this->disk->exists($versionFilename)) { $this->disk->delete($versionFilename); } $this->disk->move($temp, $versionFilename); } } }