|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace App\Model; |
|
4
|
|
|
|
|
5
|
|
|
use App\Common\Helper; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class MediaFile |
|
9
|
|
|
* |
|
10
|
|
|
* @property integer $id |
|
11
|
|
|
* @property string $file |
|
12
|
|
|
* @property string $file_info |
|
13
|
|
|
* @property integer $created_by |
|
14
|
|
|
* @property integer $updated_by |
|
15
|
|
|
* @property \Carbon\Carbon $created_at |
|
16
|
|
|
* @property \Carbon\Carbon $updated_at |
|
17
|
|
|
* |
|
18
|
|
|
* @package App\Model |
|
19
|
|
|
*/ |
|
20
|
|
|
final class MediaFile extends BaseModel |
|
21
|
|
|
{ |
|
22
|
|
|
protected $table = 'media_files'; |
|
23
|
|
|
|
|
24
|
|
|
protected $fillable = [ |
|
25
|
|
|
'file', |
|
26
|
|
|
'file_info', |
|
27
|
|
|
'created_by', |
|
28
|
|
|
'updated_by', |
|
29
|
|
|
'created_at', |
|
30
|
|
|
'updated_at', |
|
31
|
|
|
]; |
|
32
|
|
|
|
|
33
|
|
|
private static $allowedMimeTypes = [ |
|
34
|
|
|
'image/jpeg', |
|
35
|
|
|
'image/png', |
|
36
|
|
|
]; |
|
37
|
|
|
|
|
38
|
|
|
private static $allowedExt = [ |
|
39
|
|
|
'jpg', |
|
40
|
|
|
'png', |
|
41
|
|
|
'jpeg', |
|
42
|
|
|
]; |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Create new MediaFile instance and save it |
|
46
|
|
|
* |
|
47
|
|
|
* @param \Slim\Http\UploadedFile $file |
|
48
|
|
|
* @param string $uploadPath |
|
49
|
|
|
* |
|
50
|
|
|
* @return MediaFile|null |
|
51
|
|
|
* @throws \Exception |
|
52
|
|
|
*/ |
|
53
|
|
|
public static function create($file, $uploadPath) |
|
54
|
|
|
{ |
|
55
|
|
|
if (!is_dir($uploadPath) || !is_writable($uploadPath)) { |
|
56
|
|
|
throw new \Exception(sprintf('The directory `%s` is not good', $uploadPath)); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
$uploadFileName = $file->getClientFilename(); |
|
60
|
|
|
$uploadMimeType = $file->getClientMediaType(); |
|
61
|
|
|
$pieces = explode('.', $uploadFileName); |
|
62
|
|
|
$ext = end($pieces); |
|
63
|
|
|
|
|
64
|
|
|
if ( |
|
65
|
|
|
!in_array($uploadMimeType, self::$allowedMimeTypes) |
|
66
|
|
|
|| !in_array($ext, self::$allowedExt) |
|
67
|
|
|
) { |
|
68
|
|
|
throw new \Exception('This type of files is not supported'); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
$mediaFile = new self([ |
|
72
|
|
|
'file' => Helper::generateRandomString().'.'.$ext, |
|
73
|
|
|
]); |
|
74
|
|
|
|
|
75
|
|
|
$file->moveTo($uploadPath.'/'.$mediaFile->file); |
|
76
|
|
|
|
|
77
|
|
|
$mediaFile->file_info = json_encode([ |
|
78
|
|
|
'mime' => $uploadMimeType, |
|
79
|
|
|
'size' => $file->getSize(), |
|
80
|
|
|
]); |
|
81
|
|
|
|
|
82
|
|
|
if (!$mediaFile->save()) { |
|
83
|
|
|
return null; |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
return $mediaFile; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|