banki.test/models/Image.php

79 lines
1.8 KiB
PHP
Raw Permalink Normal View History

<?php
namespace app\models;
use Anper\Iuliia\Iuliia;
use Yii;
2024-08-20 07:53:49 +02:00
use yii\helpers\FileHelper;
use yii\web\BadRequestHttpException;
2024-08-20 07:53:49 +02:00
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);
if (!preg_match('/^[a-z0-9-_]+(|\.[\w\d]+)$/i', Iuliia::translate($file->name, Iuliia::WIKIPEDIA))) {
throw new BadRequestHttpException('Filename must be a-Z0-9_-!');
}
2024-08-20 07:53:49 +02:00
$new = new Image([
'sha256' => $hash,
'original_name' => Iuliia::translate($file->name, Iuliia::WIKIPEDIA),
2024-08-20 07:53:49 +02:00
'mime' => FileHelper::getMimeType($file->tempName)
]);
$new->save(true);
return $new;
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['sha256', 'original_name'], 'required'],
2024-08-21 10:08:20 +02:00
[['original_name'], 'match', 'pattern' => '/^[a-z0-9-_]+(|\.[\w\d]+)$/i'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'sha256' => 'Sha256',
'original_name' => 'Original Name',
];
}
}