Passed
Pull Request — master (#1065)
by
unknown
03:45
created

LfmPath::files()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace UniSharp\LaravelFilemanager;
4
5
use Illuminate\Container\Container;
6
use Intervention\Image\Facades\Image;
7
use Symfony\Component\HttpFoundation\File\UploadedFile;
8
use UniSharp\LaravelFilemanager\Events\FileIsUploading;
9
use UniSharp\LaravelFilemanager\Events\FileWasUploaded;
10
use UniSharp\LaravelFilemanager\Events\ImageIsUploading;
11
use UniSharp\LaravelFilemanager\Events\ImageWasUploaded;
12
use Illuminate\Support\Str;
13
use UniSharp\LaravelFilemanager\LfmUploadValidator;
14
15
class LfmPath
16
{
17
    private $working_dir;
18
    private $item_name;
19
    private $is_thumb = false;
20
21
    private $helper;
22
23
    public function __construct(Lfm $lfm = null)
24
    {
25
        $this->helper = $lfm;
26
    }
27
28
    public function __get($var_name)
29
    {
30
        if ($var_name == 'storage') {
31
            return $this->helper->getStorage($this->path('url'));
0 ignored issues
show
Bug introduced by
The method getStorage() 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

31
            return $this->helper->/** @scrutinizer ignore-call */ getStorage($this->path('url'));

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...
32
        }
33
    }
34
35
    public function __call($function_name, $arguments)
36
    {
37
        return $this->storage->$function_name(...$arguments);
0 ignored issues
show
Bug Best Practice introduced by
The property storage does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __get, consider adding a @property annotation.
Loading history...
38
    }
39
40
    public function dir($working_dir)
41
    {
42
        $this->working_dir = $working_dir;
43
44
        return $this;
45
    }
46
47
    public function thumb($is_thumb = true)
48
    {
49
        $this->is_thumb = $is_thumb;
50
51
        return $this;
52
    }
53
54
    public function setName($item_name)
55
    {
56
        $this->item_name = $item_name;
57
58
        return $this;
59
    }
60
61
    public function getName()
62
    {
63
        return $this->item_name;
64
    }
65
66
    public function path($type = 'storage')
67
    {
68
        if ($type == 'working_dir') {
69
            // working directory: /{user_slug}
70
            return $this->translateToLfmPath($this->normalizeWorkingDir());
71
        } elseif ($type == 'url') {
72
            // storage: files/{user_slug}
73
            // storage without folder: {user_slug}
74
            return $this->helper->getCategoryName() === '.'
75
                ? ltrim($this->path('working_dir'), '/')
76
                : $this->helper->getCategoryName() . $this->path('working_dir');
77
        } elseif ($type == 'storage') {
78
            // storage: files/{user_slug}
79
            // storage on windows: files\{user_slug}
80
            return str_replace(Lfm::DS, $this->helper->ds(), $this->path('url'));
81
        } else {
82
            // absolute: /var/www/html/project/storage/app/files/{user_slug}
83
            // absolute on windows: C:\project\storage\app\files\{user_slug}
84
            return $this->storage->rootPath() . $this->path('storage');
0 ignored issues
show
Bug Best Practice introduced by
The property storage does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The method rootPath() 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

84
            return $this->storage->/** @scrutinizer ignore-call */ rootPath() . $this->path('storage');

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...
85
        }
86
    }
87
88
    public function translateToLfmPath($path)
89
    {
90
        return str_replace($this->helper->ds(), Lfm::DS, $path);
91
    }
92
93
    public function url()
94
    {
95
        return $this->storage->url($this->path('url'));
0 ignored issues
show
Bug Best Practice introduced by
The property storage does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __get, consider adding a @property annotation.
Loading history...
96
    }
97
98
    public function folders()
99
    {
100
        $all_folders = array_map(function ($directory_path) {
101
            return $this->pretty($directory_path, true);
102
        }, $this->storage->directories());
0 ignored issues
show
Bug Best Practice introduced by
The property storage does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The method directories() does not exist on UniSharp\LaravelFilemanager\LfmStorageRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

102
        }, $this->storage->/** @scrutinizer ignore-call */ directories());
Loading history...
103
104
        $folders = array_filter($all_folders, function ($directory) {
105
            return $directory->name !== $this->helper->getThumbFolderName();
106
        });
107
108
        return $this->sortByColumn($folders);
109
    }
110
111
    public function files()
112
    {
113
        $files = array_map(function ($file_path) {
114
            return $this->pretty($file_path);
115
        }, $this->storage->files());
0 ignored issues
show
Bug introduced by
The method files() does not exist on UniSharp\LaravelFilemanager\LfmStorageRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

115
        }, $this->storage->/** @scrutinizer ignore-call */ files());
Loading history...
Bug Best Practice introduced by
The property storage does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __get, consider adding a @property annotation.
Loading history...
116
117
        return $this->sortByColumn($files);
118
    }
119
120
    public function pretty($item_path, $isDirectory = false)
121
    {
122
        return Container::getInstance()->makeWith(LfmItem::class, [
123
            'lfm' => (clone $this)->setName($this->helper->getNameFromPath($item_path)),
124
            'helper' => $this->helper,
125
            'isDirectory' => $isDirectory
126
        ]);
127
    }
128
129
    public function delete()
130
    {
131
        if ($this->isDirectory()) {
132
            return $this->storage->deleteDirectory();
0 ignored issues
show
Bug introduced by
The method deleteDirectory() does not exist on UniSharp\LaravelFilemanager\LfmStorageRepository. Since you implemented __call, consider adding a @method annotation. ( 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 $this->storage->/** @scrutinizer ignore-call */ deleteDirectory();
Loading history...
Bug Best Practice introduced by
The property storage does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __get, consider adding a @property annotation.
Loading history...
133
        } else {
134
            return $this->storage->delete();
0 ignored issues
show
Bug introduced by
The method delete() does not exist on UniSharp\LaravelFilemanager\LfmStorageRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

134
            return $this->storage->/** @scrutinizer ignore-call */ delete();
Loading history...
135
        }
136
    }
137
138
    /**
139
     * Create folder if not exist.
140
     *
141
     * @param  string  $path  Real path of a directory.
142
     * @return bool
143
     */
144
    public function createFolder()
145
    {
146
        if ($this->storage->exists($this)) {
0 ignored issues
show
Bug introduced by
The method exists() does not exist on UniSharp\LaravelFilemanager\LfmStorageRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

146
        if ($this->storage->/** @scrutinizer ignore-call */ exists($this)) {
Loading history...
Bug Best Practice introduced by
The property storage does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __get, consider adding a @property annotation.
Loading history...
147
            return false;
148
        }
149
150
        $this->storage->makeDirectory(0777, true, true);
151
    }
152
153
    public function isDirectory()
154
    {
155
        $working_dir = $this->path('working_dir');
156
        $parent_dir = substr($working_dir, 0, strrpos($working_dir, '/'));
157
158
        $parent_directories = array_map(function ($directory_path) {
159
            return app(static::class)->translateToLfmPath($directory_path);
0 ignored issues
show
Bug introduced by
The function app was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

159
            return /** @scrutinizer ignore-call */ app(static::class)->translateToLfmPath($directory_path);
Loading history...
160
        }, app(static::class)->dir($parent_dir)->directories());
0 ignored issues
show
Bug introduced by
The function app was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

160
        }, /** @scrutinizer ignore-call */ app(static::class)->dir($parent_dir)->directories());
Loading history...
161
162
        return in_array($this->path('url'), $parent_directories);
163
    }
164
165
    /**
166
     * Check a folder and its subfolders is empty or not.
167
     *
168
     * @param  string  $directory_path  Real path of a directory.
169
     * @return bool
170
     */
171
    public function directoryIsEmpty()
172
    {
173
        return count($this->storage->allFiles()) == 0;
0 ignored issues
show
Bug introduced by
The method allFiles() does not exist on UniSharp\LaravelFilemanager\LfmStorageRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

173
        return count($this->storage->/** @scrutinizer ignore-call */ allFiles()) == 0;
Loading history...
Bug Best Practice introduced by
The property storage does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __get, consider adding a @property annotation.
Loading history...
174
    }
175
176
    public function normalizeWorkingDir()
177
    {
178
        $path = $this->working_dir
179
            ?: $this->helper->input('working_dir')
180
            ?: $this->helper->getRootFolder();
181
182
        if ($this->is_thumb) {
183
            // Prevent if working dir is "/" normalizeWorkingDir will add double "//" that breaks S3 functionality
184
            $path = rtrim($path, Lfm::DS) . Lfm::DS . $this->helper->getThumbFolderName();
185
        }
186
187
        if ($this->getName()) {
188
            // Prevent if working dir is "/" normalizeWorkingDir will add double "//" that breaks S3 functionality
189
            $path = rtrim($path, Lfm::DS) . Lfm::DS . $this->getName();
190
        }
191
192
        return $path;
193
    }
194
195
    /**
196
     * Sort files and directories.
197
     *
198
     * @param  mixed  $arr_items  Array of files or folders or both.
199
     * @return array of object
200
     */
201
    public function sortByColumn($arr_items)
202
    {
203
        $sort_by = $this->helper->input('sort_type');
204
        if (in_array($sort_by, ['name', 'time'])) {
205
            $key_to_sort = $sort_by;
206
        } else {
207
            $key_to_sort = 'name';
208
        }
209
210
        uasort($arr_items, function ($a, $b) use ($key_to_sort) {
211
            return strcasecmp($a->{$key_to_sort}, $b->{$key_to_sort});
212
        });
213
214
        return $arr_items;
215
    }
216
217
    public function error($error_type, $variables = [])
218
    {
219
        throw new \Exception($this->helper->error($error_type, $variables));
220
    }
221
222
    // Upload section
223
    public function upload($file)
224
    {
225
        $new_file_name = $this->getNewName($file);
226
        $new_file_path = $this->setName($new_file_name)->path('absolute');
227
228
        event(new FileIsUploading($new_file_path));
0 ignored issues
show
Bug introduced by
The function event was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

228
        /** @scrutinizer ignore-call */ 
229
        event(new FileIsUploading($new_file_path));
Loading history...
229
        event(new ImageIsUploading($new_file_path));
230
        try {
231
            
232
            $this->setName($new_file_name)->storage->save($file);
0 ignored issues
show
Bug Best Practice introduced by
The property storage does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The method save() 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

232
            $this->setName($new_file_name)->storage->/** @scrutinizer ignore-call */ 
233
                                                     save($file);

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...
233
            
234
            //----- Rezise image
235
            $original_image = $this->pretty($new_file_name);
236
            $image = Image::make($original_image->get())->resize(800, 600,function ($constraint) {
237
                $constraint->aspectRatio();
238
            });
239
            $this->setName($new_file_name)->storage->put($image->stream());
0 ignored issues
show
Bug introduced by
The method put() does not exist on UniSharp\LaravelFilemanager\LfmStorageRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

239
            $this->setName($new_file_name)->storage->/** @scrutinizer ignore-call */ 
240
                                                     put($image->stream());
Loading history...
240
241
            $this->generateThumbnail($new_file_name);
242
        } catch (\Exception $e) {
243
            \Log::info($e);
244
            return $this->error('invalid');
245
        }
246
        // TODO should be "FileWasUploaded"
247
        event(new FileWasUploaded($new_file_path));
248
        event(new ImageWasUploaded($new_file_path));
249
250
        return $new_file_name;
251
    }
252
253
    public function validateUploadedFile($file)
254
    {
255
        $validator = new LfmUploadValidator($file);
256
257
        $validator->sizeLowerThanIniMaximum();
258
259
        $validator->uploadWasSuccessful();
260
261
        if (!config('lfm.over_write_on_duplicate')) {
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

261
        if (!/** @scrutinizer ignore-call */ config('lfm.over_write_on_duplicate')) {
Loading history...
262
            $validator->nameIsNotDuplicate($this->getNewName($file), $this);
263
        }
264
265
        $validator->isNotExcutable();
266
267
        if (config('lfm.should_validate_mime', false)) {
268
            $validator->mimeTypeIsValid($this->helper->availableMimeTypes());
269
        }
270
271
        if (config('lfm.should_validate_size', false)) {
272
            $validator->sizeIsLowerThanConfiguredMaximum($this->helper->maxUploadSize());
273
        }
274
275
        return true;
276
    }
277
278
    private function getNewName($file)
279
    {
280
        $new_file_name = $this->helper->translateFromUtf8(
281
            trim($this->helper->utf8Pathinfo($file->getClientOriginalName(), "filename"))
282
        );
283
284
        $extension = $file->getClientOriginalExtension();
285
286
        $new_file_name = Str::slug($new_file_name, '_');
287
288
        if ($extension) {
289
            $new_file_name_with_extention = $new_file_name . '.' . $extension;
290
        }
291
292
        if (config('lfm.rename_duplicates') === true) {
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

292
        if (/** @scrutinizer ignore-call */ config('lfm.rename_duplicates') === true) {
Loading history...
293
            $counter = 1;
294
            $file_name_without_extentions = $new_file_name;
295
            while ($this->setName(($extension) ? $new_file_name_with_extention : $new_file_name)->exists()) {
0 ignored issues
show
Bug introduced by
The method exists() does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

295
            while ($this->setName(($extension) ? $new_file_name_with_extention : $new_file_name)->/** @scrutinizer ignore-call */ exists()) {
Loading history...
Comprehensibility Best Practice introduced by
The variable $new_file_name_with_extention does not seem to be defined for all execution paths leading up to this point.
Loading history...
296
                if (config('lfm.alphanumeric_filename') === true) {
297
                    $suffix = '_'.$counter;
298
                } else {
299
                    $suffix = " ({$counter})";
300
                }
301
                $new_file_name = $file_name_without_extentions.$suffix;
302
303
                if ($extension) {
304
                    $new_file_name_with_extention = $new_file_name . '.' . $extension;
305
                }
306
                $counter++;
307
            }
308
        }
309
310
        return ($extension) ? $new_file_name_with_extention : $new_file_name;
311
    }
312
313
    public function generateThumbnail($file_name)
314
    {
315
        $original_image = $this->pretty($file_name);
316
317
        if (!$original_image->shouldCreateThumb()) {
318
            return;
319
        }
320
321
        // create folder for thumbnails
322
        $this->setName(null)->thumb(true)->createFolder();
323
324
        // generate cropped image content
325
        $this->setName($file_name)->thumb(true);
326
        $thumbWidth = $this->helper->shouldCreateCategoryThumb() && $this->helper->categoryThumbWidth() ? $this->helper->categoryThumbWidth() : config('lfm.thumb_img_width', 200);
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

326
        $thumbWidth = $this->helper->shouldCreateCategoryThumb() && $this->helper->categoryThumbWidth() ? $this->helper->categoryThumbWidth() : /** @scrutinizer ignore-call */ config('lfm.thumb_img_width', 200);
Loading history...
327
        $thumbHeight = $this->helper->shouldCreateCategoryThumb() && $this->helper->categoryThumbHeight() ? $this->helper->categoryThumbHeight() : config('lfm.thumb_img_height', 200);
328
        $image = Image::make($original_image->get())
329
            ->fit($thumbWidth, $thumbHeight);
330
331
        $this->storage->put($image->stream()->detach(), 'public');
0 ignored issues
show
Bug Best Practice introduced by
The property storage does not exist on UniSharp\LaravelFilemanager\LfmPath. Since you implemented __get, consider adding a @property annotation.
Loading history...
332
    }
333
}
334