banki.test/models/ParameterForm.php

75 lines
1.9 KiB
PHP

<?php
namespace app\models;
use Exception;
use yii\base\Model;
use yii\web\UploadedFile;
class ParameterForm extends Model
{
public $title;
public $type;
public ?UploadedFile $icon = null;
public ?UploadedFile $iconGray = null;
public function rules()
{
return [
[['title'],'string'],
[['type'], 'integer', 'min' => 1, 'max' => 2],
[['icon', 'iconGray'], 'file', 'mimeTypes' => 'image/*', 'maxSize' => 1024 * 1024, 'maxFiles' => 1],
];
}
public function load($data, $formName = null)
{
return $this->setAttributes([
'title' => $data['ParameterForm']['title'],
'type' => $data['ParameterForm']['type'],
'icon' => UploadedFile::getInstance($this, 'icon'),
'iconGray' => UploadedFile::getInstance($this, 'iconGray'),
]);
}
public function create(): int
{
$param = new Parameter();
if (!$this->title && !$this->type) {
throw new Exception('title and type are required');
}
$this->edit($param);
return $param->id;
}
public function edit(Parameter $param): void
{
if ($this->title) {
$param->title = $this->title;
}
if ($this->type) {
$param->type = (int) $this->type;
}
if ($param->type == 2) {
if ($this->icon) {
$icon = Image::fromUploadedFile($this->icon);
$param->icon_id = $icon->id;
}
if ($this->iconGray) {
$iconGray = Image::fromUploadedFile($this->iconGray);
$param->icon_gray_id = $iconGray->id;
}
} else {
$param->icon_id = null;
$param->icon_gray_id = null;
}
$param->setAttributes([
'title' => $param->title,
'type' => $param->type,
]);
$param->save();
}
}