banki.test/models/Image.php

73 lines
1.4 KiB
PHP
Raw Normal View History

<?php
namespace app\models;
use Yii;
2024-08-20 07:53:49 +02:00
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';
}
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;
}
/**
* {@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',
];
}
}