portal.mkgtu.ru/common/components/imageCropper/actions/UploadAction.php

105 lines
4.1 KiB
PHP
Raw Permalink Normal View History

2024-03-28 09:51:45 +03:00
<?php
namespace common\components\imageCropper\actions;
use yii\base\Action;
use yii\base\DynamicModel;
use yii\base\InvalidConfigException;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\web\UploadedFile;
use common\components\imageCropper\Widget;
use yii\imagine\Image;
use Imagine\Image\Box;
use Yii;
class UploadAction extends Action
{
public $path;
public $url;
public $uploadParam = 'file';
public $maxSize = 2097152;
public $extensions = 'jpeg, jpg, png, gif';
public $width = 200;
public $height = 200;
public $jpegQuality = 100;
public $pngCompressionLevel = 1;
public function init()
{
if ($this->url === null) {
throw new InvalidConfigException(Yii::t('cropper', 'MISSING_ATTRIBUTE: `Атрибут "{attribute}" должен быть указан`', ['attribute' => 'url']));
} else {
$this->url = rtrim((string)$this->url, '/') . '/';
}
if ($this->path === null) {
throw new InvalidConfigException(Yii::t('cropper', 'MISSING_ATTRIBUTE: `Атрибут "{attribute}" должен быть указан`', ['attribute' => 'path']));
} else {
$this->path = rtrim(Yii::getAlias($this->path), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
}
public function run()
{
if (Yii::$app->request->isPost) {
$file = UploadedFile::getInstanceByName($this->uploadParam);
$model = new DynamicModel(compact($this->uploadParam));
$model->addRule($this->uploadParam, 'image', [
'maxSize' => $this->maxSize,
'tooBig' => Yii::t('cropper', 'TOO_BIG_ERROR: `Превышен допустимый размер загружаемого файла ({size} Мб)`', ['size' => $this->maxSize / (1024 * 1024)]),
'extensions' => explode(', ', $this->extensions),
'wrongExtension' => Yii::t('cropper', 'EXTENSION_ERROR: `Разрешены только следующие форматы файлов: {formats}`', ['formats' => $this->extensions])
])->validate();
if ($model->hasErrors()) {
$result = [
'error' => $model->getFirstError($this->uploadParam)
];
} else {
$model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension;
$request = Yii::$app->request;
$width = $request->post('width', $this->width);
$height = $request->post('height', $this->height);
$image = Image::crop(
$file->tempName . $request->post('filename'),
intval($request->post('w')),
intval($request->post('h')),
[$request->post('x'), $request->post('y')]
)->resize(
new Box($width, $height)
);
if (!file_exists($this->path) || !is_dir($this->path)) {
$result = [
'error' => Yii::t('cropper', 'ERROR_NO_SAVE_DIR: `Директория для сохранения не существует`')]
;
} else {
$saveOptions = ['jpeg_quality' => $this->jpegQuality, 'png_compression_level' => $this->pngCompressionLevel];
if ($image->save($this->path . $model->{$this->uploadParam}->name, $saveOptions)) {
$result = [
'filelink' => $this->url . $model->{$this->uploadParam}->name
];
} else {
$result = [
'error' => Yii::t('cropper', 'ERROR_CAN_NOT_UPLOAD_FILE: `Невозможно загрузить файл`')
];
}
}
}
Yii::$app->response->format = Response::FORMAT_JSON;
return $result;
} else {
throw new BadRequestHttpException(Yii::t('cropper', 'ONLY_POST_REQUEST: `Допускается только POST-запрос`'));
}
}
}