Passed
Push — master ( 313357...ac97c7 )
by Stream
08:55 queued 04:47
created

LfmPath::__get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
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 UniSharp\LaravelFilemanager\LfmUploadValidator;
13
14
class LfmPath
15
{
16
    private $working_dir;
17
    private $item_name;
18
    private $is_thumb = false;
19
20
    private $helper;
21
22
    public function __construct(Lfm $lfm = null)
23
    {
24
        $this->helper = $lfm;
25
    }
26
27
    public function __get($var_name)
28
    {
29
        if ($var_name == 'storage') {
30
            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

30
            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...
31
        }
32
    }
33
34
    public function __call($function_name, $arguments)
35
    {
36
        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...
37
    }
38
39
    public function dir($working_dir)
40
    {
41
        $this->working_dir = $working_dir;
42
43
        return $this;
44
    }
45
46
    public function thumb($is_thumb = true)
47
    {
48
        $this->is_thumb = $is_thumb;
49
50
        return $this;
51
    }
52
53
    public function setName($item_name)
54
    {
55
        $this->item_name = $item_name;
56
57
        return $this;
58
    }
59
60
    public function getName()
61
    {
62
        return $this->item_name;
63
    }
64
65
    public function path($type = 'storage')
66
    {
67
        if ($type == 'working_dir') {
68
            // working directory: /{user_slug}
69
            return $this->translateToLfmPath($this->normalizeWorkingDir());
70
        } elseif ($type == 'url') {
71
            // storage: files/{user_slug}
72
            return $this->helper->getCategoryName() . $this->path('working_dir');
73
        } elseif ($type == 'storage') {
74
            // storage: files/{user_slug}
75
            // storage on windows: files\{user_slug}
76
            return str_replace(Lfm::DS, $this->helper->ds(), $this->path('url'));
77
        } else {
78
            // absolute: /var/www/html/project/storage/app/files/{user_slug}
79
            // absolute on windows: C:\project\storage\app\files\{user_slug}
80
            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

80
            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...
81
        }
82
    }
83
84
    public function translateToLfmPath($path)
85
    {
86
        return str_replace($this->helper->ds(), Lfm::DS, $path);
87
    }
88
89
    public function url()
90
    {
91
        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...
92
    }
93
94
    public function folders()
95
    {
96
        $all_folders = array_map(function ($directory_path) {
97
            return $this->pretty($directory_path, true);
98
        }, $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

98
        }, $this->storage->/** @scrutinizer ignore-call */ directories());
Loading history...
99
100
        $folders = array_filter($all_folders, function ($directory) {
101
            return $directory->name !== $this->helper->getThumbFolderName();
102
        });
103
104
        return $this->sortByColumn($folders);
105
    }
106
107
    public function files()
108
    {
109
        $files = array_map(function ($file_path) {
110
            return $this->pretty($file_path);
111
        }, $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

111
        }, $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...
112
113
        return $this->sortByColumn($files);
114
    }
115
116
    public function pretty($item_path, $isDirectory = false)
117
    {
118
        return Container::getInstance()->makeWith(LfmItem::class, [
119
            'lfm' => (clone $this)->setName($this->helper->getNameFromPath($item_path)),
120
            'helper' => $this->helper,
121
            'isDirectory' => $isDirectory
122
        ]);
123
    }
124
125
    public function delete()
126
    {
127
        if ($this->isDirectory()) {
128
            return $this->storage->deleteDirectory();
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 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

128
            return $this->storage->/** @scrutinizer ignore-call */ deleteDirectory();
Loading history...
129
        } else {
130
            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

130
            return $this->storage->/** @scrutinizer ignore-call */ delete();
Loading history...
131
        }
132
    }
133
134
    /**
135
     * Create folder if not exist.
136
     *
137
     * @param  string  $path  Real path of a directory.
138
     * @return bool
139
     */
140
    public function createFolder()
141
    {
142
        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

142
        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...
143
            return false;
144
        }
145
146
        $this->storage->makeDirectory(0777, true, true);
147
    }
148
149
    public function isDirectory()
150
    {
151
        $working_dir = $this->path('working_dir');
152
        $parent_dir = substr($working_dir, 0, strrpos($working_dir, '/'));
153
154
        $parent_directories = array_map(function ($directory_path) {
155
            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

155
            return /** @scrutinizer ignore-call */ app(static::class)->translateToLfmPath($directory_path);
Loading history...
156
        }, 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

156
        }, /** @scrutinizer ignore-call */ app(static::class)->dir($parent_dir)->directories());
Loading history...
157
158
        return in_array($this->path('url'), $parent_directories);
159
    }
160
161
    /**
162
     * Check a folder and its subfolders is empty or not.
163
     *
164
     * @param  string  $directory_path  Real path of a directory.
165
     * @return bool
166
     */
167
    public function directoryIsEmpty()
168
    {
169
        return count($this->storage->allFiles()) == 0;
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 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

169
        return count($this->storage->/** @scrutinizer ignore-call */ allFiles()) == 0;
Loading history...
170
    }
171
172
    public function normalizeWorkingDir()
173
    {
174
        $path = $this->working_dir
175
            ?: $this->helper->input('working_dir')
176
            ?: $this->helper->getRootFolder();
177
178
        if ($this->is_thumb) {
179
            // Prevent if working dir is "/" normalizeWorkingDir will add double "//" that breaks S3 functionality
180
            $path = rtrim($path, Lfm::DS) . Lfm::DS . $this->helper->getThumbFolderName();
181
        }
182
183
        if ($this->getName()) {
184
            // Prevent if working dir is "/" normalizeWorkingDir will add double "//" that breaks S3 functionality
185
            $path = rtrim($path, Lfm::DS) . Lfm::DS . $this->getName();
186
        }
187
188
        return $path;
189
    }
190
191
    /**
192
     * Sort files and directories.
193
     *
194
     * @param  mixed  $arr_items  Array of files or folders or both.
195
     * @return array of object
196
     */
197
    public function sortByColumn($arr_items)
198
    {
199
        $sort_by = $this->helper->input('sort_type');
200
        if (in_array($sort_by, ['name', 'time'])) {
201
            $key_to_sort = $sort_by;
202
        } else {
203
            $key_to_sort = 'name';
204
        }
205
206
        uasort($arr_items, function ($a, $b) use ($key_to_sort) {
207
            return strcasecmp($a->{$key_to_sort}, $b->{$key_to_sort});
208
        });
209
210
        return $arr_items;
211
    }
212
213
    public function error($error_type, $variables = [])
214
    {
215
        throw new \Exception($this->helper->error($error_type, $variables));
216
    }
217
218
    // Upload section
219
    public function upload($file)
220
    {
221
        $new_file_name = $this->getNewName($file);
222
        $new_file_path = $this->setName($new_file_name)->path('absolute');
223
224
        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

224
        /** @scrutinizer ignore-call */ 
225
        event(new FileIsUploading($new_file_path));
Loading history...
225
        event(new ImageIsUploading($new_file_path));
226
        try {
227
            $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

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

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

274
        if (/** @scrutinizer ignore-call */ config('lfm.rename_file') === true) {
Loading history...
275
            $new_file_name = uniqid();
276
        } elseif (config('lfm.alphanumeric_filename') === true) {
277
            $new_file_name = preg_replace('/[^A-Za-z0-9\-\']/', '_', $new_file_name);
278
        }
279
280
        if ($extension) {
281
            $new_file_name_with_extention = $new_file_name . '.' . $extension;
282
        }
283
284
        if (config('lfm.rename_duplicates') === true) {
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