Passed
Push — dev5 ( 848ae0...7a0764 )
by Ron
08:15
created

LinkFilesController::store()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 59
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 3.1707

Importance

Changes 0
Metric Value
cc 3
eloc 30
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 59
ccs 22
cts 30
cp 0.7332
crap 3.1707
rs 9.44

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 16
            $this->user = auth()->user();
30 16
            $this->authorize('hasAccess', 'Use File Links');
31 10
            return $next($request);
32 22
        });
33 22
    }
34
35
    //  Add a file to the file link
36 2
    public function store(Request $request)
37
    {
38 2
        $request->validate([
39 2
            'linkID' => 'required|exists:file_links,link_id'
40
        ]);
41
42 2
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
43
44
        //  Verify that the upload is valid and being processed
45 2
        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 2
        $save = $receiver->receive();
55
56
        //  See if the uploade has finished
57 2
        if($save->isFinished())
58
        {
59 2
            $filePath = config('filesystems.paths.links').DIRECTORY_SEPARATOR.$request->linkID;
60 2
            $file = $save->getFile();
61
62
            //  Clean the file and store it
63 2
            $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
64 2
            $file->storeAs($filePath, $fileName);
65
66
            //  Place file in Files table of DB
67 2
            $newFile = Files::create([
68 2
                'file_name' => $fileName,
69 2
                'file_link' => $filePath.DIRECTORY_SEPARATOR
70
            ]);
71 2
            $fileID = $newFile->file_id;
72
73
            //  Place the file in the file link files table of DB
74 2
            FileLinkFiles::create([
75 2
                'link_id'  => $request->linkID,
76 2
                'file_id'  => $fileID,
77 2
                'user_id'  => Auth::user()->user_id,
78 2
                'upload'   => 0
79
            ]);
80
81
            //  Log stored file
82 2
            Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath.DIRECTORY_SEPARATOR.$fileName]);
83
84 2
            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 2
    public function show($id)
100
    {
101 2
        $files = new FileLinkFilesCollection(
102 2
            FileLinkFiles::where('link_id', $id)
103 2
            ->orderBy('user_id', 'ASC')
104 2
            ->orderBy('created_at', 'ASC')
105 2
            ->with('Files')
106 2
            ->with('User')
107 2
            ->get()
108
        );
109
110 2
        return $files;
111
    }
112
113
    //  Move a file to a customer file
114 4
    public function update(Request $request, $id)
115
    {
116 4
        $request->validate([
117 4
            'fileID'   => 'required',
118
            'fileName' => 'required',
119
            'fileType' => 'required'
120
        ]);
121
122 4
        $linkData = FileLinks::find($id);
123
124 4
        $newPath = config('filesystems.paths.customers').DIRECTORY_SEPARATOR.$linkData->cust_id.DIRECTORY_SEPARATOR;
125 4
        $fileData = Files::find($request->fileID);
126
127
        //  Verify that the file does not already exist in the customerdata or file
128 4
        $dup = CustomerFiles::where('file_id', $request->fileID)->where('cust_id', $linkData->cust_id)->count();
129 4
        if($dup || Storage::exists($newPath.$fileData->file_name))
130
        {
131 2
            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 4
            Storage::move($fileData->file_link.$fileData->file_name, $newPath.$fileData->file_name);
138
        }
139 2
        catch(\Exception $e)
140
        {
141 2
            report($e);
142 2
            return response()->json(['success' => false, 'reason' => 'Cannot Find File']);
143
        }
144
145
        //  Update the file path in the database
146 2
        $fileData->update([
147 2
            'file_link' => $newPath
148
        ]);
149
150
        //  Place the file in the customer database
151 2
        CustomerFiles::create([
152 2
            'file_id'      => $request->fileID,
153 2
            'file_type_id' => $request->fileType,
154 2
            'cust_id'      => $linkData->cust_id,
155 2
            'user_id'      => Auth::user()->user_id,
156 2
            'name'         => $request->fileName
157
        ]);
158
159 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
160 2
        Log::debug('File Data - ', $request->toArray());
161 2
        Log::info('File ID-'.$request->fileId.' moved to customer ID-'.$linkData->cust_id.' for link ID-'.$id);
162 2
        return response()->json(['success' => true]);
163
    }
164
165
    //  Delete a file attached to a link
166 2
    public function destroy($id)
167
    {
168
        //  Get the necessary file information and delete it from the database
169 2
        $fileData = FileLinkFiles::find($id);
170 2
        $fileID   = $fileData->file_id;
171 2
        $fileData->delete();
172
173
        //  Delete the file from the folder (not, will not delete if in use elsewhere)
174 2
        Files::deleteFile($fileID);
175
176 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
177 2
        Log::info('File ID-'.$fileData->file_id.' deleted for Link ID-'.$fileData->link_id);
178 2
        return response()->json(['success' => true]);
179
    }
180
}
181