Test Failed
Push — dev5 ( d8a4d3...9629db )
by Ron
08:46
created

FileLinksController::store()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 67
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 5.0536

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 33
nc 4
nop 1
dl 0
loc 67
ccs 27
cts 31
cp 0.871
crap 5.0536
rs 9.0808
c 1
b 0
f 0

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 Carbon\Carbon;
7
use App\FileLinks;
8
use App\FileLinkFiles;
9
use App\CustomerFileTypes;
10
use Illuminate\Support\Str;
11
use Illuminate\Http\Request;
12
use Illuminate\Http\UploadedFile;
13
use Illuminate\Support\Facades\Log;
14
use Illuminate\Support\Facades\Auth;
15
use App\Http\Controllers\Controller;
16
use Illuminate\Support\Facades\Route;
17
use Illuminate\Support\Facades\Storage;
18
use App\Http\Resources\FileLinksCollection;
19
use App\Http\Resources\CustomerFileTypesCollection;
20
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
21
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
22
use App\Http\Resources\FileLinks as FileLinksResource;
23
24
class FileLinksController extends Controller
25
{
26
    //  Only authorized users have access
27
    public function __construct()
28
    {
29 76
        //  Verify the user is logged in and has permissions for this page
30
        $this->middleware('auth');
31
        $this->middleware(function($request, $next) {
32 76
            $this->user = auth()->user();
0 ignored issues
show
Bug Best Practice introduced by
The property user does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
33
            $this->authorize('hasAccess', 'Use File Links');
34 58
            return $next($request);
35 58
        });
36 40
    }
37 76
38 76
    //  Landing page shows all links that the user owns
39
    public function index()
40
    {
41 2
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
42
        return view('links.index');
43 2
    }
44 2
45
    //  Ajax call to show the links for a specific user
46
    public function find($id)
47
    {
48 8
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
49
50 8
        //  Verify if the user is trying to pull their own links
51
        if($id == 0)
52
        {
53 8
            $id = Auth::user()->user_id;
54
        }
55 2
        //  If the user is trying to pull someone elses links, they must be able to manage users
56
        else if($id != Auth::user()->user_id)
57
        {
58 6
            $this->authorize('hasAccess', 'manage_users');
59
        }
60 4
61
        $links = new FileLinksCollection(
62
            FileLinks::where('user_id', $id)
63 6
                ->withCount('FileLinkFiles')
64 6
                ->orderBy('expire', 'desc')->get()
65 6
        );
66 6
67
        Log::debug('File links for User ID - '.$id.': ', array($links));
68
69 6
        return $links;
70
    }
71
72
    //  Create a new file link form
73 2
    public function create()
74
    {
75 2
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
76 2
        return view('links.newLink');
77
    }
78
79
    //  Submit the new file link form
80 12
    public function store(Request $request)
81
    {
82 12
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name.'. Submitted Data - ', $request->toArray());
83
84 12
        $request->validate([
85 12
            'name'       => 'required',
86
            'expire'     => 'required',
87
            'customerID' => 'exists:customers,cust_id|nullable'
88
        ]);
89
90 8
        //  If there are files, process them first in their chunks
91
        if(!empty($request->file))
92 2
        {
93
            $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
94
95 2
            //  Recieve and process the file
96
            $save = $receiver->receive();
97
98 2
            //  See if the uploade has finished
99
            if($save->isFinished())
100 2
            {
101 2
                $this->saveFile($save->getFile());
102
                return response()->json(['upload_success' => true]);
103
            }
104
105
            //  Get the current progress if the file is not done being uploaded
106
            $handler = $save->handler();
107
108
            Log::debug('File being uploaded.  Percentage done - '.$handler->getPercentageDone());
109
            return response()->json([
110
                'done'   => $handler->getPercentageDone(),
111
                'status' => true
112
            ]);
113
        }
114
115 8
        // //  If there are no files being uploaded or the file uploade process is done
116
        $linkID = $this->createLink($request);
117 8
        if($request->session()->has('newLinkFile'))
118 8
        {
119
            //  If there were files uploaded to the link, process them
120
            $files = session('newLinkFile');
121 2
            $path = config('filesystems.paths.links').DIRECTORY_SEPARATOR.$linkID;
122 2
123
            foreach($files as $file)
124 2
            {
125
                $data = Files::find($file);
126 2
                //  Move the file to the proper folder
127
                Storage::move($data->file_link.$data->file_name, $path.DIRECTORY_SEPARATOR.$data->file_name);
128 2
                //  Update file link in DB
129
                $data->update([
130 2
                    'file_link' => $path.DIRECTORY_SEPARATOR
131 2
                ]);
132
                //  Attach file to the link
133
                FileLinkFiles::create([
134 2
                    'link_id' => $linkID,
135 2
                    'file_id' => $data->file_id,
136 2
                    'user_id' => Auth::user()->user_id,
137 2
                    'upload' => 0
138 2
                ]);
139
140
                Log::info('File Added for link ID - '.$linkID.' by '.Auth::user()->full_name.'.  File ID-'.$data->file_id);
141 2
            }
142
143
            $request->session()->forget('newLinkFile');
144 2
        }
145
146
        return response()->json(['link' => $linkID, 'name' => Str::slug($request->name)]);
147 8
    }
148
149
    //  Create the new file link
150
    private function createLink($data)
151
    {
152
        //  Generate a random hash to use as the file link and make sure it is not already in use
153
        do
154 8
        {
155
            $hash = strtolower(Str::random(15));
156 8
            $dup  = FileLinks::where('link_hash', $hash)->get()->count();
157
            Log::debug('New possible link hash - '.$hash.'. Is duplicate -> '.$dup == 0 ? 'false' : 'true');
158
        } while($dup != 0);
159
160
        //  Create the new file link
161 8
        $link = FileLinks::create([
162 8
            'user_id'      => Auth::user()->user_id,
163 8
            'cust_id'      => $data->customerID,
164
            'link_hash'    => $hash,
165
            'link_name'    => $data->name,
166 8
            'expire'       => $data->expire,
167 8
            'allow_upload' => isset($data->allowUp) && $data->allowUp ? true : false,
168 8
            'note'         => $data->instructions
169 8
        ]);
170 8
171 8
        Log::info('File Link Created for '.Auth::user()->full_name.'.  Link Data - ', $link->toArray());
172 8
173 8
        return $link->link_id;
174
    }
175
176 8
    //  Save a file attached to the link
177
    private function saveFile(UploadedFile $file)
178 8
    {
179
        Log::debug('Preparing to save file. File Data - ', array($file));
180
        $filePath = config('filesystems.paths.links').DIRECTORY_SEPARATOR.'_tmp';
181
        Log:debug('File will be saved to '.$filePath);
182 2
183
        //  Clean the file and store it
184 2
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
185
        $file->storeAs($filePath, $fileName);
186 2
187
        //  Place file in Files table of DB
188
        $newFile = Files::create([
189 2
            'file_name' => $fileName,
190 2
            'file_link' => $filePath.DIRECTORY_SEPARATOR
191
        ]);
192
        $fileID = $newFile->file_id;
193 2
194 2
        //  Save the file ID in the session array
195 2
        $fileArr = session('newLinkFile') != null ? session('newLinkFile') : [];
196
        $fileArr[] = $fileID;
197 2
        session(['newLinkFile' => $fileArr]);
198
199
        //  Log stored file
200 2
        Log::info('File Stored by '.Auth::user()->full_name, ['file_id' => $fileID, 'file_path' => $filePath.DIRECTORY_SEPARATOR, 'file_name' => $fileName]);
201 2
        return $fileID;
202 2
    }
203
204
    //  Show details about a file link
205 2
    public function details($id, /** @scrutinizer ignore-unused */ $name)
206 2
    {
207
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
208
209
        //  Verify that the link is a valid link
210 4
        $linkData = FileLinks::find($id);
211
        $fileTypes = new CustomerFileTypesCollection(CustomerFileTypes::all());
212 4
213
        //  If the link is invalid, return an error page
214
        if(empty($linkData))
215 4
        {
216 4
            Log::warning('User '.Auth::user()->full_name.' tried to view bad file link', ['user_id' => Auth::user()->user_id, 'link_id' => $id]);
217
            return view('links.badLink');
218
        }
219 4
220
        return view('links.details', [
221 2
            'link_id'    => $linkData->link_id,
222 2
            'cust_id'    => $linkData->cust_id,
223
            'file_types' => $fileTypes
224
        ]);
225 2
    }
226 2
227 2
228 2
229
230
231
232
233 2
234
235 2
236
237 2
    //  Ajax call te get JSON details of the link
238 2
    public function show($id)
239
    {
240
        $linkData = new FileLinksResource(FileLinks::find($id));
241
242 6
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
243
        return $linkData;
244 6
    }
245
246 6
    //  Update the link's details
247 6
    public function update(Request $request, $id)
248
    {
249
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name.'. Submitted Data - ', $request->toArray());
250
251
        $request->validate([
252 2
            'name'       => 'required',
253 2
            'expire'     => 'required',
254 2
            'customerTag' => 'exists:customers,cust_id|nullable'
255 2
        ]);
256 2
257 2
        FileLinks::find($id)->update([
258
            'link_name'    => $request->name,
259
            'expire'       => $request->expire,
260 2
            'allow_upload' => isset($request->allowUpload) && $request->allowUpload ? true : false,
261
            'cust_id'      => $request->customerTag,
262 2
            'note'         => $request->hasInstructions ? $request->instructions : null
263
        ]);
264
265
        Log::info('File Link Updated by '.Auth::user()->full_name, ['link_id' => $id]);
266 2
267
        return response()->json(['success' => true]);
268
    }
269 2
270 2
    //  Disable a file linke, but do not remove it (set the expire date to a previous date)
271
    public function disableLink($id)
272
    {
273 2
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
274 2
275 2
        //  update the expire date for the link
276
        FileLinks::find($id)->update([
277
            'expire' => Carbon::yesterday()
278
        ]);
279 2
280
        Log::info('User '.Auth::user()->full_name.' disabled link ID - '.$id);
281
        return response()->json(['success' => true]);
282 2
    }
283 2
284
    //  Delete a file link
285 2
    public function destroy($id)
286
    {
287 2
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
288 2
289
        //  Remove any files from database
290
        $data = FileLinkFiles::where('link_id', $id)->get();
291 2
        if(!$data->isEmpty())
292
        {
293
            foreach($data as $file)
294
            {
295 2
                $fileID = $file->file_id;
296
                $file->delete();
297 2
                Log::debug('File link file ID '.$file->file_id.' deleted from Link ID '.$id);
298 2
299
                //  Delete the file if it is no longer in use
300 2
                Files::deleteFile($fileID);
301 2
            }
302
        }
303
304
        FileLinks::find($id)->delete();
305
306
        Log::info('File link ID - '.$id.' deleted by '.Auth::user()->full_name);
307
308
        return response()->json([
309
            'success' => true
310
        ]);
311
    }
312
}
313