Passed
Push — dev5 ( c2dc0b...cbc2fc )
by Ron
08:19
created

FilesDomain::processFileChunk()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0116

Importance

Changes 0
Metric Value
cc 2
eloc 6
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 12
ccs 6
cts 7
cp 0.8571
crap 2.0116
rs 10
1
<?php
2
3
namespace App\Domains;
4
5
use Illuminate\Support\Facades\Log;
6
use Illuminate\Support\Facades\Auth;
7
use Illuminate\Support\Facades\Storage;
8
use Illuminate\Http\UploadedFile;
9
10
use App\Files;
11
12
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
13
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
14
15
class FilesDomain
16
{
17
    protected $receiver, $path, $fileID;
18
19
    //  Constructor will set a default path location in the event one is not set through child class
20 34
    public function __construct()
21
    {
22 34
        $this->path = config('filesystems.paths.default');
23 34
    }
24
25
    //  Process a file chunk
26 2
    protected function processFileChunk($data)
27
    {
28 2
        $this->receiver = new FileReceiver('file', $data, HandlerFactory::classFromRequest($data));
29
30 2
        $save = $this->receiver->receive();
31 2
        if($save->isFinished())
32
        {
33 2
            $fileID = $this->saveFile($save->getFile());
34 2
            return $fileID;
35
        }
36
37
        return false;
38
    }
39
40
    //  Save a file after it has been uploaded
41 16
    protected function saveFile(UploadedFile $file)
42
    {
43 16
        $fileName = $this->cleanFilename($file->getClientOriginalName());
44 16
        $fileName = $this->isFileDup($fileName);
45 16
        $file->storeAs($this->path, $fileName);
46
47
        //  Place file in Files table of DB
48 16
        $newFile = Files::create([
49 16
            'file_name' => $fileName,
50 16
            'file_link' => $this->path.DIRECTORY_SEPARATOR
51
        ]);
52
53 16
        $user = isset(Auth::user()->full_name) ? Auth::user()->full_name : \Request::ip();
54 16
        Log::info('New file stored in database by '.$user.'. File Data - ', array($newFile));
55 16
        return  $newFile->file_id;
56
    }
57
58
    //  Try to delete a file - note this will fail if it is still in use
59 4
    protected function deleteFile($fileID)
60
    {
61
        try
62
        {
63
            //  Try to delete file from database - will throw error if foreign key is in use
64 4
            $fileData = Files::find($fileID);
65 4
            $fileLink = $fileData->file_link.$fileData->file_name;
66 4
            $fileData->delete();
67
        }
68
        catch(\Illuminate\Database\QueryException $e)
69
        {
70
            //  Unable to remove file from the database
71
            Log::warning('Attempt to delete file failed.  Reason - '.$e.'. Additional File Data - ', ['file_id' => $fileID, 'file_name' => $fileLink, 'user_id' => Auth::user()->user_id]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fileLink does not seem to be defined for all execution paths leading up to this point.
Loading history...
72
            return false;
73
        }
74
75
        //  Delete the file from the storage system
76 4
        Storage::delete($fileLink);
77
78 4
        Log::notice('File deleted by '.Auth::user()->full_name.'. File Information - ', ['file_id' => $fileID, 'file_name' => $fileLink, 'user_id' => Auth::user()->user_id]);
79 4
        return true;
80
    }
81
82
    //  Clean a file name to remove any spaces
83 16
    protected function cleanFilename($name)
84
    {
85
        //  Remove all spaces
86 16
        $fileName = str_replace(' ', '_', $name);
87 16
        Log::debug('Cleaning filename.  Old name - '.$name.'.  New Name - '.$fileName);
88
89 16
        return $fileName;
90
    }
91
92
    //  Determine if the already exists and should be appended
93 16
    protected function isFileDup($fileName)
94
    {
95
        //  Determine if the filename already exists
96 16
        if (Storage::exists($this->path . DIRECTORY_SEPARATOR . $fileName))
97
        {
98
            $fileParts = pathinfo($fileName);
99
            $extension = isset($fileParts['extension']) ? ('.' . $fileParts['extension']) : '';
100
101
            //  Look to see if a number is already appended to a file.  (example - file(1).pdf)
102
            if (preg_match('/(.*?)(\d+)$/', $fileParts['filename'], $match))
103
            {
104
                // Has a number, increment it
105
                $base = $match[1];
106
                $number = intVal($match[2]);
107
            }
108
            else
109
            {
110
                // No number, add one
111
                $base = $fileParts['filename'];
112
                $number = 0;
113
            }
114
115
            //  Increase the number until one that is not in use is found
116
            do
117
            {
118
                $fileName = $base . '(' . ++$number . ')' . $extension;
119
            } while (Storage::exists($this->path.DIRECTORY_SEPARATOR.$fileName));
120
        }
121
122 16
        return $fileName;
123
    }
124
125
    //  When multiple files are uploaded at once, they are placed in a temporary location.  This moves them to the final folder
126 6
    protected function moveFile($newPath, $fileID)
127
    {
128 6
        $data = Files::find($fileID);
129
        //  Move the file to the proper folder
130
        try{
131 6
            Log::debug('Attempting to moving file '.$fileID.' to '.$newPath);
132 6
            Storage::move($data->file_link.$data->file_name, $newPath.DIRECTORY_SEPARATOR.$data->file_name);
133
        }
134 2
        catch(\Exception $e)
135
        {
136 2
            report($e);
137 2
            return false;
138
        }
139 4
        Log::info('Moved file '.$data->file_name.'from '.$data->file_link.' to new location - '.$newPath.'.  File Details - ', array($data));
140
141
        //  Update file link in DB
142 4
        $data->update([
143 4
            'file_link' => $newPath.DIRECTORY_SEPARATOR
144
        ]);
145
146 4
        return true;
147
    }
148
}
149