2024-08-19 11:24:25 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace app\models;
|
|
|
|
|
2024-08-21 09:58:35 +02:00
|
|
|
use Anper\Iuliia\Iuliia;
|
2024-08-19 11:24:25 +02:00
|
|
|
use Yii;
|
2024-08-20 07:53:49 +02:00
|
|
|
use yii\helpers\FileHelper;
|
2024-08-21 09:58:35 +02:00
|
|
|
use yii\web\BadRequestHttpException;
|
2024-08-20 07:53:49 +02:00
|
|
|
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);
|
|
|
|
|
2024-08-21 09:58:35 +02:00
|
|
|
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,
|
2024-08-21 09:58:35 +02:00
|
|
|
'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;
|
|
|
|
}
|
|
|
|
|
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'],
|
2024-08-21 10:08:20 +02:00
|
|
|
[['original_name'], 'match', 'pattern' => '/^[a-z0-9-_]+(|\.[\w\d]+)$/i'],
|
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
|
|
|
];
|
|
|
|
}
|
|
|
|
}
|