Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
PosTrait
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
3 / 3
7
100.00% covered (success)
100.00%
1 / 1
 fileRename
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 FileProcessing
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
4
 supportsWebp
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3namespace App\Traits;
4
5use Intervention\Image\Facades\Image;
6
7trait PosTrait
8{
9    public static function fileRename()
10    {
11        return now()->format('Y-m-d') . 'a_n' . time() . rand(1111, 9999);
12    }
13
14    /**
15     * Resize into the given bounding box (aspect-ratio kept, never upscaled)
16     * and re-encode to WebP when the server's GD build supports it — smaller
17     * files than the original JPEG/PNG upload, same visual quality at this
18     * quality setting. GIFs are moved as-is (animation would be lost through
19     * Intervention v2's static resize/encode path). Falls back to saving in
20     * the original format on a host without WebP support instead of
21     * throwing, so this never blocks an upload.
22     */
23    public static function FileProcessing($file, $folderPath = null, $maxWidth = 600, $maxHeight = 600, int $quality = 82)
24    {
25        $dynamicPath = public_path($folderPath);
26        if (! file_exists($dynamicPath)) {
27            mkdir($dynamicPath, 0777, true);
28        }
29
30        $extension = strtolower($file->getClientOriginalExtension());
31
32        if ($extension === 'gif') {
33            $fileName = self::fileRename() . '.gif';
34            $file->move($dynamicPath, $fileName);
35
36            return $folderPath . $fileName;
37        }
38
39        $outExtension = self::supportsWebp() ? 'webp' : $extension;
40        $fileName = self::fileRename() . '.' . $outExtension;
41
42        Image::make($file->path())
43            ->resize($maxWidth, $maxHeight, function ($constraint) {
44                $constraint->aspectRatio();
45                $constraint->upsize();
46            })
47            ->save($dynamicPath . '/' . $fileName, $quality);
48
49        return $folderPath . $fileName;
50    }
51
52    private static function supportsWebp(): bool
53    {
54        return function_exists('imagewebp') || extension_loaded('imagick');
55    }
56}