Passed
Push — dev5 ( 1fbf2b...8c60e2 )
by Ron
09:02
created

LinkFilesController::store()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 51
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 2.0145

Importance

Changes 0
Metric Value
cc 2
eloc 26
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 51
ccs 22
cts 26
cp 0.8462
crap 2.0145
rs 9.504

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