Passed
Push — master ( 94f9e4...52fcb5 )
by PRATIK
03:11
created

Thumbnail::imageDetail()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 25
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 11
Bugs 5 Features 0
Metric Value
cc 4
eloc 21
c 11
b 5
f 0
nc 8
nop 3
dl 0
loc 25
rs 9.584
1
<?php
2
3
namespace drh2so4\Thumbnail\Traits;
4
5
use Carbon\Carbon;
6
use Illuminate\Support\Facades\File;
7
use Intervention\Image\Facades\Image as Image;
8
9
trait Thumbnail
10
{
11
    public function makeThumbnail($fieldname = 'image', $custom = [])
12
    {
13
        if (!empty(request()->$fieldname) || $custom['image']) {
14
            /* ------------------------------------------------------------------- */
15
16
            $image_file = $custom['image'] ?? request()->file($fieldname); // Retriving Image File
17
            $extension = $this->image_info($image_file)->extension; //Retriving Image extension
18
            $imageStoreNameOnly = $this->validImageName($this->image_info($image_file)->imageStoreNameOnly); //Making Image Store name
19
20
            /* ------------------------------------------------------------------- */
21
22
            /* ----------------------------------------Parent Image Upload----------------------------------------- */
23
            $this->uploadImage($fieldname, $custom); // Upload Parent Image
24
            /* --------------------------------------------------------------------------------------------- */
25
            if (config('thumbnail.thumbnail', true)) {
26
                $thumbnails = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $thumbnails is dead and can be removed.
Loading history...
27
                $thumbnails = $custom['thumbnails'] ?? config('thumbnail.thumbnails') ?? false; // Grab Thumbnails
28
                $storage = $custom['storage'] ?? config('thumbnail.storage_path', 'uploads') ?? false; // Grab Storage Info
29
                if ($thumbnails) {
30
                    /* -----------------------------------------Custom Thumbnails------------------------------------------------- */
31
                    $this->makeCustomThumbnails($image_file, $imageStoreNameOnly, $extension, $storage, $thumbnails);
32
                    /* -------------------------------------------------------------------------------------------------- */
33
                } else {
34
                    /* ---------------------------------------Default Thumbnails--------------------------------------- */
35
                    $this->makeDefaultThumbnails($image_file, $extension, $imageStoreNameOnly);
36
                    /* ------------------------------------------------------------------------------------------------ */
37
                }
38
            }
39
        }
40
    }
41
42
    // Make Image
43
    private function makeImg($image_file, $name, $location, $width, $height, $quality)
44
    {
45
        $image = $image_file->storeAs($location, $name, 'public'); // Thumbnail Storage Information
46
        $img = Image::cache(function ($cached_img) use ($image_file, $width, $height) {
47
            return $cached_img->make($image_file->getRealPath())->fit($width, $height);
48
        }, config('thumbnail.image_cached_time', 10), true); //Storing Thumbnail
49
        $img->save(public_path('storage/' . $image), $quality); //Storing Thumbnail
50
    }
51
52
    // Make Custom Thumbnail
53
    private function makeCustomThumbnails($image_file, $imageStoreNameOnly, $extension, $storage, $thumbnails)
54
    {
55
        foreach ($thumbnails as $thumbnail) {
56
            $customthumbnail = $imageStoreNameOnly . '-' . str_replace('-', '', $thumbnail['thumbnail-name']) . '.' . $extension; // Making Thumbnail Name
57
            $this->makeImg(
58
                $image_file,
59
                $customthumbnail,
60
                $storage,
61
                (int) $thumbnail['thumbnail-width'],
62
                (int) $thumbnail['thumbnail-height'],
63
                (int) $thumbnail['thumbnail-quality']
64
            );
65
        }
66
    }
67
68
    // Make Default Thumbnail
69
    private function makeDefaultThumbnails($image_file, $extension, $imageStoreNameOnly)
70
    {
71
        /* --------------------- Thumbnail Info---------------------------------------- */
72
        //small thumbnail name
73
        $smallthumbnail = $imageStoreNameOnly . '-small' . '.' . $extension; // Making Thumbnail Name
74
75
        //medium thumbnail name
76
        $mediumthumbnail = $imageStoreNameOnly . '-medium' . '.' . $extension; // Making Thumbnail Name
77
78
        // Medium Thumbnail
79
        $this->makeImg(
80
            $image_file,
81
            $mediumthumbnail,
82
            config('thumbnail.storage_path', 'uploads'),
83
            config('thumbnail.medium_thumbnail_width', 800),
84
            config('thumbnail.medium_thumbnail_height', 600),
85
            config('thumbnail.medium_thumbnail_quality', 60)
86
        );
87
88
        // Small Thumbnail
89
        $this->makeImg(
90
            $image_file,
91
            $smallthumbnail,
92
            config('thumbnail.storage_path', 'uploads'),
93
            config('thumbnail.small_thumbnail_width', 800),
94
            config('thumbnail.small_thumbnail_height', 600),
95
            config('thumbnail.small_thumbnail_quality', 60)
96
        );
97
98
        /* ------------------------------------------------------------------------------------- */
99
    }
100
101
    /* Image Upload Process Info */
102
    private function image_info($image_file)
103
    {
104
        $filenamewithextension = $image_file->getClientOriginalName(); //Retriving Full Image Name
105
        $raw_filename = pathinfo($filenamewithextension, PATHINFO_FILENAME); //Retriving Image Raw Filename only
106
        $filename = str_replace(['-', ' '], '', $raw_filename); // Retrive Filename
107
        $extension = $image_file->getClientOriginalExtension(); //Retriving Image extension
108
        $imageStoreNameOnly = $filename . '-' . time(); //Making Image Store name
109
        $imageStoreName = $filename . '-' . time() . '.' . $extension; //Making Image Store name
110
111
        $image_info['filenamewithextension'] = $filenamewithextension;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$image_info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $image_info = array(); before regardless.
Loading history...
112
        $image_info['raw_filename'] = $raw_filename;
113
        $image_info['filename'] = $filename;
114
        $image_info['extension'] = $extension;
115
        $image_info['imageStoreNameOnly'] = $imageStoreNameOnly;
116
        $image_info['imageStoreName'] = $imageStoreName;
117
118
        return json_decode(json_encode($image_info));
119
    }
120
121
    // Upload Parent Image
122
    public function uploadImage($fieldname = 'image', $custom = [])
123
    {
124
        $image_file = $custom['image'] ?? request()->file($fieldname); // Retriving Image File
125
        $img = $custom['image'] ?? request()->$fieldname;
126
        $imageStoreName = $this->image_info($image_file)->imageStoreName;
127
        $this->update([
0 ignored issues
show
Bug introduced by
It seems like update() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

127
        $this->/** @scrutinizer ignore-call */ 
128
               update([
Loading history...
128
            $fieldname => $img->storeAs($custom['storage'] ?? config('thumbnail.storage_path', 'uploads'), $imageStoreName, 'public'), // Storing Parent Image
129
        ]);
130
131
        $image = Image::cache(function ($cached_img) use ($image_file, $custom) {
132
            return $cached_img->make($image_file->getRealPath())->fit($custom['width'] ?? config('thumbnail.img_width', 1000), $custom['height'] ?? config('thumbnail.img_height', 800)); //Parent Image Interventing
0 ignored issues
show
Bug introduced by
The method getRealPath() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

132
            return $cached_img->make($image_file->/** @scrutinizer ignore-call */ getRealPath())->fit($custom['width'] ?? config('thumbnail.img_width', 1000), $custom['height'] ?? config('thumbnail.img_height', 800)); //Parent Image Interventing

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
133
        }, config('thumbnail.image_cached_time', 10), true);
134
        $image->save(public_path('storage/' . $this->$fieldname), $custom['quality'] ?? config('thumbnail.image_quality', 80)); // Parent Image Locating Save
135
    }
136
137
    // Thumbnail Path
138
    public function thumbnail($fieldname = 'image', $size = null, $byLocation = false)
139
    {
140
        return $this->imageDetail($fieldname, $size, $byLocation)->path;
141
    }
142
143
    /* Checking Image Existance */
144
    private function imageExists($image)
145
    {
146
        return file_exists($image->getRealPath());
147
    }
148
149
    // Checking Image's Thumbnail Existance
150
    public function hasThumbnail($fieldname = 'image', $size = null)
151
    {
152
        return $this->imageDetail($fieldname, $size)->property->has_thumbnail;
153
    }
154
155
    // Thumbnail Count
156
    public function thumbnailCount($fieldname = 'image', $size = null)
157
    {
158
        return $this->hasThumbnail($fieldname, $size) ? $this->imageDetail($fieldname, $size)->property->thumbnail_count : 0;
159
    }
160
161
    /* Image Details */
162
    public function imageDetail($fieldname = 'image', $size = null, $byLocation = false)
163
    {
164
        $location = $byLocation ? $fieldname : null; // Search By Location Condition
165
        $image = $byLocation ? ($location ?? $this->$fieldname) : $this->$fieldname; // Search By Field or Location
166
        $path = explode('/', $image);
167
        $extension = \File::extension($image);
168
        $name = basename($image, '.' . $extension);
169
        $image_fullname = isset($size) ? $name . '-' . (string) $size . '.' . $extension : $name . '.' . $extension;
170
        array_pop($path);
171
        $location = implode('/', $path);
172
        $path = 'storage/' . $location . '/' . $image_fullname;
173
        $image_files = File::files(public_path('storage/' . $location));
174
        $images_property = $this->imageProperty($image_files, $name);
175
        $image_detail = [
176
            'image'     => $image,
177
            'name'      => $name,
178
            'fullname'  => $image_fullname,
179
            'extension' => $extension,
180
            'path'      => $path,
181
            'directory' => public_path('storage/' . $location),
182
            'location'  => public_path('storage/' . $image),
183
            'property'  => $images_property,
184
        ];
185
186
        return json_decode(json_encode($image_detail));
187
    }
188
189
    // Image Property
190
    private function imageProperty($image_files, $parent_name)
191
    {
192
        $images_property = [];
193
        $thumbnails_property = [];
194
        $thumbnail_count = 0;
195
        foreach ($image_files as $image) {
196
            $image_partition = explode('-', basename($image));
197
            if (isset($image_partition[0]) && isset($image_partition[1])) {
198
                $parent_thumbnail_name = $image_partition[0] . '-' . $image_partition[1];
199
                if ($parent_name == $parent_thumbnail_name) {
200
                    $thumbnail_count++;
201
                    $thumbnail_exists = $this->imageExists($image);
202
                    if (isset($image_partition[2])) {
203
                        $thumbnails_property['image'] = $image->getFilename() ?? null;
204
                        $thumbnails_property['real_name'] = $image_partition[0];
205
                        $thumbnails_property['size'] = $image->getSize();
206
                        $thumbnails_property['created_date'] = isset($image_partition[1]) ? Carbon::createFromFormat('Y/m/d H:i:s', date('Y/m/d H:i:s', (int) $image_partition[1])) : null;
207
                        $thumbnails_property['directory'] = $image->getPath();
208
                        $thumbnails_property['location'] = $image->getRealPath();
209
                        $images_property['has_thumbnail'] = $thumbnail_exists || $this->imageExists($image);
210
                        $images_property['thumbnail_count'] = $thumbnail_count;
211
                        $thumbnails[] = $thumbnails_property;
212
                        $images_property['thumbnails'] = $thumbnails;
213
                    }
214
                } elseif ($image->getFileNameWithoutExtension() == $parent_name) {
215
                    $images_property['has_thumbnail'] = ($thumbnail_exists ?? false);
216
                    $images_property['real_name'] = $image_partition[0];
217
                    $images_property['size'] = $image->getSize();
218
                    $images_property['directory'] = $image->getPath();
219
                    $images_property['location'] = $image->getRealPath();
220
                } else {
221
                    false;
222
                }
223
            }
224
        }
225
226
        return $images_property;
227
    }
228
229
    // Hard Delete
230
    public function hardDelete($fieldname = 'image'): void
231
    {
232
        if (File::exists($this->imageDetail($fieldname)->location)) {
233
            if ($this->imageDetail($fieldname)->property->has_thumbnail) {
234
                foreach ($this->imageDetail($fieldname)->property->thumbnails as $thumbnail) {
235
                    File::exists($thumbnail->location) ? File::delete($thumbnail->location) : '';
236
                }
237
            }
238
            File::exists($this->imageDetail($fieldname)->location) ? File::delete($this->imageDetail($fieldname)->location) : false;
239
        }
240
    }
241
242
    // Hard Delete with Parent
243
    public function hardDeleteWithParent($fieldname = 'image'): void
244
    {
245
        $this->hardDelete($fieldname);
246
        $this->delete();
0 ignored issues
show
Bug introduced by
It seems like delete() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

246
        $this->/** @scrutinizer ignore-call */ 
247
               delete();
Loading history...
247
    }
248
249
    // Valid Image Name
250
    private function validImageName($name)
251
    {
252
        return strtolower(str_replace([' ', '-', '$', '<', '>', '&', '{', '}', '*', '\\', '/', ':' . ';', ',', "'", '"'], '_', trim($name)));
253
    }
254
}
255