Test Failed
Push — dev5 ( 054b32...4c0df5 )
by Ron
12:54
created

LinkFilesController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.216

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 8
ccs 2
cts 5
cp 0.4
crap 1.216
rs 10
1
<?php
2
3
namespace App\Http\Controllers\FileLinks;
4
5
use App\Files;
6
use App\FileLinks;
7
use App\FileLinkFiles;
8
use App\CustomerFiles;
9
use Illuminate\Http\Request;
10
use Illuminate\Support\Facades\Log;
11
use App\Http\Controllers\Controller;
12
use Illuminate\Support\Facades\Auth;
13
use Illuminate\Support\Facades\Route;
14
use Illuminate\Support\Facades\Storage;
15
use App\Http\Resources\FileLinkFilesCollection;
16
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
17
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
18
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
19
20
class LinkFilesController extends Controller
21
{
22
    private $user;
23
24 22
    public function __construct()
25
    {
26
        //  Verify the user is logged in and has permissions for this page
27 22
        $this->middleware('auth');
28
        $this->middleware(function($request, $next) {
29
            $this->user = auth()->user();
30
            $this->authorize('hasAccess', 'Use File Links');
31
            return $next($request);
32 22
        });
33 22
    }
34
35
    //  Add a file to the file link
36
    public function store(Request $request)
37
    {
38
        $request->validate([
39
            'linkID' => 'required|exists:file_links,link_id'
40
        ]);
41
42
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
43
44
        //  Verify that the upload is valid and being processed
45
        if($receiver->isUploaded() === false)
46
        {
47
            Log::error('Upload File Missing - ' .
48
            /** @scrutinizer ignore-type */
49
            $request->toArray());
50
            throw new UploadMissingFileException();
51
        }
52
53
        //  Recieve and process the file
54
        $save = $receiver->receive();
55
56
        //  See if the uploade has finished
57
        if($save->isFinished())
58
        {
59
            $filePath = config('filesystems.paths.links').DIRECTORY_SEPARATOR.$request->linkID;
60
            $file = $save->getFile();
61
62
            //  Clean the file and store it
63
            $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
64
            $file->storeAs($filePath, $fileName);
65
66
            //  Place file in Files table of DB
67
            $newFile = Files::create([
68
                'file_name' => $fileName,
69
                'file_link' => $filePath.DIRECTORY_SEPARATOR
70
            ]);
71
            $fileID = $newFile->file_id;
72
73
            //  Place the file in the file link files table of DB
74
            FileLinkFiles::create([
75
                'link_id'  => $request->linkID,
76
                'file_id'  => $fileID,
77
                'user_id'  => Auth::user()->user_id,
78
                'upload'   => 0
79
            ]);
80
81
            //  Log stored file
82
            Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath.DIRECTORY_SEPARATOR.$fileName]);
83
84
            return response()->json(['success' => true]); ;
85
        }
86
87
        //  Get the current progress
88
        $handler = $save->handler();
89
90
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
91
        Log::debug('File being uploaded.  Percentage done - '.$handler->getPercentageDone());
92
        return response()->json([
93
            'done'   => $handler->getPercentageDone(),
94
            'status' => true
95
        ]);
96
    }
97
98
    //  Show the files attached to a link
99
    public function show($id)
100
    {
101
        $files = new FileLinkFilesCollection(
102
            FileLinkFiles::where('link_id', $id)
103
            ->orderBy('user_id', 'ASC')
104
            ->orderBy('created_at', 'ASC')
105
            ->with('Files')
106
            ->with('User')
107
            ->get()
108
        );
109
110
        return $files;
111
    }
112
113
    //  Move a file to a customer file
114
    public function update(Request $request, $id)
115
    {
116
        $request->validate([
117
            'fileID'   => 'required',
118
            'fileName' => 'required',
119
            'fileType' => 'required'
120
        ]);
121
122
        $linkData = FileLinks::find($id);
123
124
        $newPath = config('filesystems.paths.customers').DIRECTORY_SEPARATOR.$linkData->cust_id.DIRECTORY_SEPARATOR;
125
        $fileData = Files::find($request->fileID);
126
127
        //  Verify that the file does not already exist in the customerdata or file
128
        $dup = CustomerFiles::where('file_id', $request->fileID)->where('cust_id', $linkData->cust_id)->count();
129
        if($dup || Storage::exists($newPath.$fileData->file_name))
130
        {
131
            return response()->json(['success' => 'false', 'reason' => 'This File Already Exists in Customer Files']);
132
        }
133
134
        //  Move the file to the customrs file folder
135
        try
136
        {
137
            Storage::move($fileData->file_link.$fileData->file_name, $newPath.$fileData->file_name);
138
        }
139
        catch(\Exception $e)
140
        {
141
            report($e);
142
            return response()->json(['success' => false, 'reason' => 'Cannot Find File']);
143
        }
144
145
        //  Update the file path in the database
146
        $fileData->update([
147
            'file_link' => $newPath
148
        ]);
149
150
        //  Place the file in the customer database
151
        CustomerFiles::create([
152
            'file_id'      => $request->fileID,
153
            'file_type_id' => $request->fileType,
154
            'cust_id'      => $linkData->cust_id,
155
            'user_id'      => Auth::user()->user_id,
156
            'name'         => $request->fileName
157
        ]);
158
159
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
160
        Log::debug('File Data - ', $request->toArray());
161
        Log::info('File ID-'.$request->fileId.' moved to customer ID-'.$linkData->cust_id.' for link ID-'.$id);
162
        return response()->json(['success' => true]);
163
    }
164
165
    //  Delete a file attached to a link
166
    public function destroy($id)
167
    {
168
        //  Get the necessary file information and delete it from the database
169
        $fileData = FileLinkFiles::find($id);
170
        $fileID   = $fileData->file_id;
171
        $fileData->delete();
172
173
        //  Delete the file from the folder (not, will not delete if in use elsewhere)
174
        Files::deleteFile($fileID);
175
176
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
177
        Log::info('File ID-'.$fileData->file_id.' deleted for Link ID-'.$fileData->link_id);
178
        return response()->json(['success' => true]);
179
    }
180
}
181