MicroFrameWork/kernel/FormModel.php

92 lines
1.8 KiB
PHP
Raw Normal View History

2024-07-24 14:07:45 +03:00
<?php
namespace kernel;
use MadeSimple\Validator\Validator;
class FormModel
{
protected Validator $validator;
protected array $data = [];
public function __construct()
{
$this->validator = new Validator();
}
public function rules(): array
{
return [];
}
public function load(array $array): void
{
$rules = $this->rules();
foreach ($array as $key => $item) {
if (isset($rules[$key])) {
$this->data[$key] = $item;
}
}
}
public function getData(): array
{
return $this->data;
}
2024-09-10 12:55:41 +03:00
public function setItem(string $name, string|int $value): void
{
$this->data[$name] = $value;
}
2024-07-24 14:07:45 +03:00
public function getItem(string $name)
{
2024-10-17 14:55:00 +03:00
if (isset($this->data[$name])) {
2024-07-24 14:07:45 +03:00
return $this->data[$name];
}
return null;
}
public function validate(): bool
{
$res = $this->validator->validate($this->data, $this->rules());
if (!$res) {
return true;
}
return false;
}
2024-12-03 12:13:18 +03:00
public function validateForUpdate(): bool
{
$res = $this->validator->validate($this->data, $this->rulesForUpdate());
if (!$res) {
return true;
}
return false;
}
2024-07-24 14:07:45 +03:00
public function getErrors(): array
{
return $this->validator->getProcessedErrors();
}
2024-10-17 14:55:00 +03:00
public function getErrorsStr(): string
{
$errorsArr = $this->getErrors();
$str = '';
if ($errorsArr['errors']) {
foreach ($errorsArr['errors'] as $key => $errorArr) {
foreach ($errorsArr['errors'][$key] as $error){
$str .= "$error <br>";
}
}
}
return $str;
}
2024-07-24 14:07:45 +03:00
}