n_oct/plugins/rainlab/builder/classes/ModelFormModel.php

94 lines
2.0 KiB
PHP
Raw Normal View History

2023-06-18 12:28:15 +00:00
<?php namespace RainLab\Builder\Classes;
2023-06-17 20:52:33 +00:00
use SystemException;
2023-06-18 12:28:15 +00:00
use ValidationException;
2023-06-17 20:52:33 +00:00
/**
2023-06-18 12:28:15 +00:00
* Represents and manages model forms.
2023-06-17 20:52:33 +00:00
*
* @package rainlab\builder
* @author Alexey Bobkov, Samuel Georges
*/
class ModelFormModel extends ModelYamlModel
{
public $controls;
protected static $fillable = [
'fileName',
'controls'
];
protected $validationRules = [
'fileName' => ['required', 'regex:/^[a-z0-9\.\-_]+$/i']
];
public function loadForm($path)
{
$this->fileName = $path;
return parent::load($this->getFilePath());
}
public function fill(array $attributes)
{
if (!is_array($attributes['controls'])) {
$attributes['controls'] = json_decode($attributes['controls'], true);
if ($attributes['controls'] === null) {
throw new SystemException('Cannot decode controls JSON string.');
}
}
return parent::fill($attributes);
}
public static function validateFileIsModelType($fileContentsArray)
{
$modelRootNodes = [
'fields',
'tabs',
'secondaryTabs'
];
foreach ($modelRootNodes as $node) {
if (array_key_exists($node, $fileContentsArray)) {
return true;
}
}
return false;
}
public function validate()
{
parent::validate();
if (!$this->controls) {
throw new ValidationException(['controls' => 'Please create at least one field.']);
}
}
public function initDefaults()
{
$this->fileName = 'fields.yaml';
}
/**
2023-06-18 12:28:15 +00:00
* Converts the model's data to an array before it's saved to a YAML file.
2023-06-17 20:52:33 +00:00
* @return array
*/
protected function modelToYamlArray()
{
2023-06-18 12:28:15 +00:00
return $this->controls;
2023-06-17 20:52:33 +00:00
}
/**
2023-06-18 12:28:15 +00:00
* Load the model's data from an array.
2023-06-17 20:52:33 +00:00
* @param array $array An array to load the model fields from.
*/
protected function yamlArrayToModel($array)
{
$this->controls = $array;
}
}