banki.test/models/ParameterForm.php

77 lines
2.0 KiB
PHP
Raw Normal View History

2024-08-20 07:53:49 +02:00
<?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 = $icon->id;
}
if ($this->iconGray) {
$iconGray = Image::fromUploadedFile($this->iconGray);
$param->iconGray = $iconGray->id;
}
$param->setAttributes([
'icon' => $param->icon,
'iconGray' => $param->iconGray,
]);
}
$param->setAttributes([
'title' => $param->title,
'type' => $param->type,
]);
$param->save();
}
}