Passed
Pull Request — master (#1065)
by
unknown
04:05
created

LfmPath::isDirectory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 10
rs 10
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
            $this->setName($new_file_name)->storage->save($file);
0 ignored issues
show
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

231
            $this->setName($new_file_name)->storage->/** @scrutinizer ignore-call */ 
232
                                                     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...
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...
232
233
            $this->generateThumbnail($new_file_name);
234
        } catch (\Exception $e) {
235
            \Log::info($e);
236
            return $this->error('invalid');
237
        }
238
        // TODO should be "FileWasUploaded"
239
        event(new FileWasUploaded($new_file_path));
240
        event(new ImageWasUploaded($new_file_path));
241
242
        return $new_file_name;
243
    }
244
245
    public function validateUploadedFile($file)
246
    {
247
        $validator = new LfmUploadValidator($file);
248
249
        $validator->sizeLowerThanIniMaximum();
250
251
        $validator->uploadWasSuccessful();
252
253
        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

253
        if (!/** @scrutinizer ignore-call */ config('lfm.over_write_on_duplicate')) {
Loading history...
254
            $validator->nameIsNotDuplicate($this->getNewName($file), $this);
255
        }
256
257
        $validator->isNotExcutable();
258
259
        if (config('lfm.should_validate_mime', false)) {
260
            $validator->mimeTypeIsValid($this->helper->availableMimeTypes());
261
        }
262
263
        if (config('lfm.should_validate_size', false)) {
264
            $validator->sizeIsLowerThanConfiguredMaximum($this->helper->maxUploadSize());
265
        }
266
267
        return true;
268
    }
269
270
    private function getNewName($file)
271
    {
272
        $new_file_name = $this->helper->translateFromUtf8(
273
            trim($this->helper->utf8Pathinfo($file->getClientOriginalName(), "filename"))
274
        );
275
276
        $extension = $file->getClientOriginalExtension();
277
278
        $new_file_name = Str::slug($new_file_name, '_');
279
280
        if ($extension) {
281
            $new_file_name_with_extention = $new_file_name . '.' . $extension;
282
        }
283
284
        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

284
        if (/** @scrutinizer ignore-call */ config('lfm.rename_duplicates') === true) {
Loading history...
285
            $counter = 1;
286
            $file_name_without_extentions = $new_file_name;
287
            while ($this->setName(($extension) ? $new_file_name_with_extention : $new_file_name)->exists()) {
0 ignored issues
show
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...
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

287
            while ($this->setName(($extension) ? $new_file_name_with_extention : $new_file_name)->/** @scrutinizer ignore-call */ exists()) {
Loading history...
288
                if (config('lfm.alphanumeric_filename') === true) {
289
                    $suffix = '_'.$counter;
290
                } else {
291
                    $suffix = " ({$counter})";
292
                }
293
                $new_file_name = $file_name_without_extentions.$suffix;
294
295
                if ($extension) {
296
                    $new_file_name_with_extention = $new_file_name . '.' . $extension;
297
                }
298
                $counter++;
299
            }
300
        }
301
302
        return ($extension) ? $new_file_name_with_extention : $new_file_name;
303
    }
304
305
    public function generateThumbnail($file_name)
306
    {
307
        $original_image = $this->pretty($file_name);
308
309
        if (!$original_image->shouldCreateThumb()) {
310
            return;
311
        }
312
313
        // create folder for thumbnails
314
        $this->setName(null)->thumb(true)->createFolder();
315
316
        // generate cropped image content
317
        $this->setName($file_name)->thumb(true);
318
        $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

318
        $thumbWidth = $this->helper->shouldCreateCategoryThumb() && $this->helper->categoryThumbWidth() ? $this->helper->categoryThumbWidth() : /** @scrutinizer ignore-call */ config('lfm.thumb_img_width', 200);
Loading history...
319
        $thumbHeight = $this->helper->shouldCreateCategoryThumb() && $this->helper->categoryThumbHeight() ? $this->helper->categoryThumbHeight() : config('lfm.thumb_img_height', 200);
320
        $image = Image::make($original_image->get())
321
            ->fit($thumbWidth, $thumbHeight);
322
323
        $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...
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

323
        $this->storage->/** @scrutinizer ignore-call */ 
324
                        put($image->stream()->detach(), 'public');
Loading history...
324
    }
325
}
326