Completed
Push — master ( 6f46cf...3807c7 )
by Song
02:25
created

UploadField::sequenceName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Form\Field;
4
5
use Encore\Admin\Form;
6
use Illuminate\Support\Facades\Storage;
7
use Illuminate\Support\Facades\URL;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Encore\Admin\Form\Field\URL.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
use Symfony\Component\HttpFoundation\File\UploadedFile;
9
10
trait UploadField
11
{
12
    /**
13
     * Upload directory.
14
     *
15
     * @var string
16
     */
17
    protected $directory = '';
18
19
    /**
20
     * File name.
21
     *
22
     * @var null
23
     */
24
    protected $name = null;
25
26
    /**
27
     * Storage instance.
28
     *
29
     * @var \Illuminate\Filesystem\Filesystem
30
     */
31
    protected $storage = '';
32
33
    /**
34
     * If use unique name to store upload file.
35
     *
36
     * @var bool
37
     */
38
    protected $useUniqueName = false;
39
40
    /**
41
     * If use sequence name to store upload file.
42
     *
43
     * @var bool
44
     */
45
    protected $useSequenceName = false;
46
47
    /**
48
     * @var bool
49
     */
50
    protected $removable = false;
51
52
    /**
53
     * Initialize the storage instance.
54
     *
55
     * @return void.
0 ignored issues
show
Documentation introduced by
The doc-type void. could not be parsed: Unknown type name "void." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
56
     */
57
    protected function initStorage()
58
    {
59
        $this->disk(config('admin.upload.disk'));
60
    }
61
62
    /**
63
     * Set default options form image field.
64
     *
65
     * @return void
66
     */
67
    protected function setupDefaultOptions()
68
    {
69
        $defaultOptions = [
70
            'overwriteInitial'     => false,
71
            'initialPreviewAsData' => true,
72
            'browseLabel'          => trans('admin.browse'),
73
            'showRemove'           => false,
74
            'showUpload'           => false,
75
//            'initialCaption'       => $this->initialCaption($this->value),
76
            'deleteExtraData'      => [
77
                $this->formatName($this->column) => static::FILE_DELETE_FLAG,
0 ignored issues
show
Bug introduced by
The property column does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
It seems like formatName() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
78
                static::FILE_DELETE_FLAG         => '',
79
                '_token'                         => csrf_token(),
80
                '_method'                        => 'PUT',
81
            ],
82
        ];
83
84
        if ($this->form instanceof Form) {
85
            $defaultOptions['deleteUrl'] = $this->form->resource() . '/' . $this->form->model()->getKey();
0 ignored issues
show
Bug introduced by
The property form does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
86
        }
87
88
        $this->options($defaultOptions);
89
    }
90
91
    /**
92
     * Set preview options form image field.
93
     *
94
     * @return void
95
     */
96
    protected function setupPreviewOptions()
97
    {
98
        if (!$this->removable) {
99
            return;
100
        }
101
102
        $this->options([
103
            //'initialPreview'        => $this->preview(),
104
            'initialPreviewConfig' => $this->initialPreviewConfig(),
0 ignored issues
show
Bug introduced by
It seems like initialPreviewConfig() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
105
        ]);
106
    }
107
108
    /**
109
     * Allow use to remove file.
110
     *
111
     * @return $this
112
     */
113
    public function removable()
114
    {
115
        $this->removable = true;
116
117
        return $this;
118
    }
119
120
    /**
121
     * Set options for file-upload plugin.
122
     *
123
     * @param array $options
124
     *
125
     * @return $this
126
     */
127
    public function options($options = [])
128
    {
129
        $this->options = array_merge($options, $this->options);
0 ignored issues
show
Bug introduced by
The property options does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
130
131
        return $this;
132
    }
133
134
    /**
135
     * Set disk for storage.
136
     *
137
     * @param string $disk Disks defined in `config/filesystems.php`.
138
     *
139
     * @throws \Exception
140
     *
141
     * @return $this
142
     */
143
    public function disk($disk)
144
    {
145
        try {
146
            $this->storage = Storage::disk($disk);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Illuminate\Support\Facades\Storage::disk($disk) of type object<Illuminate\Contra...\Filesystem\Filesystem> is incompatible with the declared type object<Illuminate\Filesystem\Filesystem> of property $storage.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
147
        } catch (\Exception $exception) {
148
            if (!array_key_exists($disk, config('filesystems.disks'))) {
149
                admin_error(
150
                    'Config error.',
151
                    "Disk [$disk] not configured, please add a disk config in `config/filesystems.php`."
152
                );
153
154
                return $this;
155
            }
156
157
            throw $exception;
158
        }
159
160
        return $this;
161
    }
162
163
    /**
164
     * Specify the directory and name for upload file.
165
     *
166
     * @param string $directory
167
     * @param null|string $name
168
     *
169
     * @return $this
170
     */
171
    public function move($directory, $name = null)
172
    {
173
        $this->dir($directory);
174
175
        $this->name($name);
0 ignored issues
show
Bug introduced by
It seems like $name defined by parameter $name on line 171 can also be of type null; however, Encore\Admin\Form\Field\UploadField::name() does only seem to accept callable, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
176
177
        return $this;
178
    }
179
180
    /**
181
     * Specify the directory upload file.
182
     *
183
     * @param string $dir
184
     *
185
     * @return $this
186
     */
187
    public function dir($dir)
188
    {
189
        if ($dir) {
190
            $this->directory = $dir;
191
        }
192
193
        return $this;
194
    }
195
196
    /**
197
     * Set name of store name.
198
     *
199
     * @param string|callable $name
200
     *
201
     * @return $this
202
     */
203
    public function name($name)
204
    {
205
        if ($name) {
206
            $this->name = $name;
207
        }
208
209
        return $this;
210
    }
211
212
    /**
213
     * Use unique name for store upload file.
214
     *
215
     * @return $this
216
     */
217
    public function uniqueName()
218
    {
219
        $this->useUniqueName = true;
220
221
        return $this;
222
    }
223
224
    /**
225
     * Use sequence name for store upload file.
226
     *
227
     * @return $this
228
     */
229
    public function sequenceName()
230
    {
231
        $this->useSequenceName = true;
232
233
        return $this;
234
    }
235
236
    /**
237
     * Get store name of upload file.
238
     *
239
     * @param UploadedFile $file
240
     *
241
     * @return string
242
     */
243
    protected function getStoreName(UploadedFile $file)
244
    {
245
        if ($this->useUniqueName) {
246
            return $this->generateUniqueName($file);
247
        }
248
249
        if ($this->useSequenceName) {
250
            return $this->generateSequenceName($file);
251
        }
252
253
        if ($this->name instanceof \Closure) {
254
            return $this->name->call($this, $file);
255
        }
256
257
        if (is_string($this->name)) {
258
            return $this->name;
259
        }
260
261
        return $file->getClientOriginalName();
262
    }
263
264
    /**
265
     * Get directory for store file.
266
     *
267
     * @return mixed|string
268
     */
269
    public function getDirectory()
270
    {
271
        if ($this->directory instanceof \Closure) {
272
            return call_user_func($this->directory, $this->form);
273
        }
274
275
        return $this->directory ?: $this->defaultDirectory();
0 ignored issues
show
Bug introduced by
It seems like defaultDirectory() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
276
    }
277
278
    /**
279
     * Upload file and delete original file.
280
     *
281
     * @param UploadedFile $file
282
     *
283
     * @return mixed
284
     */
285
    protected function upload(UploadedFile $file)
286
    {
287
        $this->renameIfExists($file);
288
289
        return $this->storage->putFileAs($this->getDirectory(), $file, $this->name);
290
    }
291
292
    /**
293
     * If name already exists, rename it.
294
     *
295
     * @param $file
296
     *
297
     * @return void
298
     */
299
    public function renameIfExists(UploadedFile $file)
300
    {
301
        if ($this->storage->exists("{$this->getDirectory()}/$this->name")) {
302
            $this->name = $this->generateUniqueName($file);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->generateUniqueName($file) of type string is incompatible with the declared type null of property $name.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
303
        }
304
    }
305
306
    /**
307
     * Get file visit url.
308
     *
309
     * @param $path
310
     *
311
     * @return string
312
     */
313
    public function objectUrl($path)
314
    {
315
        if (URL::isValidUrl($path)) {
316
            return $path;
317
        }
318
319
        if ($this->storage) {
320
            return $this->storage->url($path);
321
        }
322
323
        return Storage::disk(config('admin.upload.disk'))->url($path);
324
    }
325
326
    /**
327
     * Generate a unique name for uploaded file.
328
     *
329
     * @param UploadedFile $file
330
     *
331
     * @return string
332
     */
333
    protected function generateUniqueName(UploadedFile $file)
334
    {
335
        return md5(uniqid()) . '.' . $file->getClientOriginalExtension();
336
    }
337
338
    /**
339
     * Generate a sequence name for uploaded file.
340
     *
341
     * @param UploadedFile $file
342
     *
343
     * @return string
344
     */
345
    protected function generateSequenceName(UploadedFile $file)
346
    {
347
        $index        = 1;
348
        $extension    = $file->getClientOriginalExtension();
349
        $originalName = $file->getClientOriginalName();
350
        $newName      = $originalName . '_' . $index . '.' . $extension;
351
352
        while ($this->storage->exists("{$this->getDirectory()}/$newName")) {
353
            ++$index;
354
            $newName = $originalName . '_' . $index . '.' . $extension;
355
        }
356
357
        return $newName;
358
    }
359
360
    /**
361
     * Destroy original files.
362
     *
363
     * @return void.
0 ignored issues
show
Documentation introduced by
The doc-type void. could not be parsed: Unknown type name "void." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
364
     */
365
    public function destroy()
366
    {
367
        if ($this->storage->exists($this->original)) {
368
            $this->storage->delete($this->original);
0 ignored issues
show
Bug introduced by
The property original does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
369
        }
370
    }
371
}
372