2024-08-19 11:24:25 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace app\models;
|
|
|
|
|
|
|
|
use Yii;
|
2024-08-20 07:53:49 +02:00
|
|
|
use yii\helpers\FileHelper;
|
|
|
|
use yii\web\UploadedFile;
|
2024-08-19 11:24:25 +02:00
|
|
|
|
|
|
|
/**
|
2024-08-19 14:44:16 +02:00
|
|
|
* This is the model class for table "image".
|
2024-08-19 11:24:25 +02:00
|
|
|
*
|
|
|
|
* @property int $id
|
2024-08-19 14:44:16 +02:00
|
|
|
* @property string $sha256
|
|
|
|
* @property string $original_name
|
2024-08-19 11:24:25 +02:00
|
|
|
*/
|
2024-08-19 14:44:16 +02:00
|
|
|
class Image extends \yii\db\ActiveRecord
|
2024-08-19 11:24:25 +02:00
|
|
|
{
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
|
|
|
public static function tableName()
|
|
|
|
{
|
2024-08-19 14:44:16 +02:00
|
|
|
return 'image';
|
2024-08-19 11:24:25 +02:00
|
|
|
}
|
|
|
|
|
2024-08-20 07:53:49 +02:00
|
|
|
public static function fromUploadedFile(?UploadedFile $file): ?Image
|
|
|
|
{
|
|
|
|
if ($file === null) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
$hash = hash_file('sha256', $file->tempName);
|
|
|
|
$existing = Image::find()->where([ 'sha256' => $hash ])->one();
|
|
|
|
if ($existing) {
|
|
|
|
return $existing;
|
|
|
|
}
|
|
|
|
|
|
|
|
copy($file->tempName, env('UPLOADS_PATH') . '/' . $hash);
|
|
|
|
|
|
|
|
$new = new Image([
|
|
|
|
'sha256' => $hash,
|
|
|
|
'original_name' => $file->name,
|
|
|
|
'mime' => FileHelper::getMimeType($file->tempName)
|
|
|
|
]);
|
|
|
|
$new->save(true);
|
|
|
|
|
|
|
|
return $new;
|
|
|
|
}
|
|
|
|
|
2024-08-19 11:24:25 +02:00
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
|
|
|
public function rules()
|
|
|
|
{
|
|
|
|
return [
|
2024-08-19 14:44:16 +02:00
|
|
|
[['sha256', 'original_name'], 'required'],
|
|
|
|
[['sha256', 'original_name'], 'string', 'max' => 255],
|
2024-08-19 11:24:25 +02:00
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
|
|
|
public function attributeLabels()
|
|
|
|
{
|
|
|
|
return [
|
|
|
|
'id' => 'ID',
|
2024-08-19 14:44:16 +02:00
|
|
|
'sha256' => 'Sha256',
|
|
|
|
'original_name' => 'Original Name',
|
2024-08-19 11:24:25 +02:00
|
|
|
];
|
|
|
|
}
|
|
|
|
}
|