banki.test/models/Image.php

73 lines
1.4 KiB
PHP

<?php
namespace app\models;
use Yii;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;
/**
* This is the model class for table "image".
*
* @property int $id
* @property string $sha256
* @property string $original_name
*/
class Image extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'image';
}
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;
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['sha256', 'original_name'], 'required'],
[['sha256', 'original_name'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'sha256' => 'Sha256',
'original_name' => 'Original Name',
];
}
}