Passed
Push — dev5a ( 9eb7a1...6555e1 )
by Ron
07:16
created

FilesDomain::checkForDuplicate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
nc 3
nop 1
dl 0
loc 16
ccs 9
cts 9
cp 1
crap 4
rs 9.9666
c 1
b 0
f 0
1
<?php
2
3
namespace App\Domains;
4
5
use Illuminate\Http\UploadedFile;
6
use Illuminate\Support\Facades\Log;
7
use Illuminate\Support\Facades\Storage;
8
9
class FilesDomain
10
{
11
    protected $path, $disk;
12
13 6
    public function __construct($path = null, $disk = 'local')
14
    {
15 6
        $this->path = $path === null ? config('filesystems.paths.default') : $path;
16 6
        $this->disk = $disk;
17 6
    }
18
19 6
    public function saveFile(UploadedFile $file)
20
    {
21 6
        $fileName = $this->cleanFileName($file->getClientOriginalName());
22 6
        $fileName = $this->checkForDuplicate($fileName);
23 6
        $file->storeAs($this->path, $fileName, $this->disk);
24
25 6
        Log::debug('New File stored.  Details - ', ['disk' => $this->disk, 'path' => $this->path, 'filename' => $fileName]);
26 6
        return $fileName;
27
    }
28
29
    //  Sanitize the filename to remove any illegal characters
30 6
    protected function cleanFileName($name)
31
    {
32 6
        return preg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $name);
33
    }
34
35
    //  Check to see if the file already exists, if so append filename as needed
36 6
    protected function checkForDuplicate($name)
37
    {
38 6
        if(Storage::disk($this->disk)->exists($this->path.DIRECTORY_SEPARATOR.$name))
39
        {
40 2
            $parts = pathinfo($name);
41 2
            $ext   = isset($parts['extension']) ? ('.'.$parts['extension']) : '';
42 2
            $base = $parts['filename'];
43 2
             $number = 0;
44
45
            do
46
            {
47 2
                $name = $base.'('.++$number.')'.$ext;
48 2
            } while(Storage::disk($this->disk)->exists($this->path.DIRECTORY_SEPARATOR.$name));
49
        }
50
51 6
        return $name;
52
    }
53
}
54