Attachment::upload()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 15
cp 0
rs 9.6333
c 0
b 0
f 0
cc 2
nc 2
nop 4
crap 6
1
<?php
2
3
namespace SET;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Facades\File;
7
use Illuminate\Support\Facades\Storage;
8
9
class Attachment extends Model
10
{
11
    protected $table = 'attachments';
12
    public $timestamps = true;
13
    protected $fillable = ['filename', 'mime', 'imageable_type', 'imageable_id', 'encrypted', 'admin_only'];
14
15
    public function imageable()
16
    {
17
        return $this->morphTo();
18
    }
19
20
    public static function upload($model, $files, $encrypted = false, $admin_only = false)
21
    {
22
        $modelName = strtolower(class_basename($model)).'_';
23
24
        foreach ($files as $file) {
25
            $data = [];
26
27
            Storage::makeDirectory($modelName.$model->id);
28
29
            Storage::disk('local')
30
                ->put($modelName.$model->id.'/'.$file->getClientOriginalName(), self::encryptFileContents($file, $encrypted));
31
32
            $data['filename'] = $file->getClientOriginalName();
33
            $data['mime'] = $file->getClientMimeType();
34
            $data['encrypted'] = $encrypted;
35
            $data['admin_only'] = $admin_only;
36
            $model->attachments()->create($data);
37
        }
38
    }
39
40
    private static function encryptFileContents($file, $encrypt)
41
    {
42
        if ($encrypt) {
43
            return encrypt(File::get($file));
44
        }
45
46
        return File::get($file);
47
    }
48
}
49