php-censor/src/Form/FieldSet.php

119 lines
2.5 KiB
PHP
Raw Permalink Normal View History

2016-04-12 19:31:39 +02:00
<?php
2018-03-04 11:50:08 +01:00
namespace PHPCensor\Form;
2016-04-20 17:39:48 +02:00
2018-02-16 14:18:04 +01:00
use PHPCensor\View;
2016-04-12 19:31:39 +02:00
class FieldSet extends Element
{
2017-11-05 15:48:36 +01:00
/**
* @var Element[]
*/
2018-01-18 15:51:33 +01:00
protected $children = [];
2016-04-20 17:39:48 +02:00
2017-11-05 15:48:36 +01:00
/**
* @return array
*/
2016-04-20 17:39:48 +02:00
public function getValues()
{
$rtn = [];
2018-01-18 15:51:33 +01:00
foreach ($this->children as $field) {
2016-04-20 17:39:48 +02:00
if ($field instanceof FieldSet) {
$fieldName = $field->getName();
if (empty($fieldName)) {
$rtn = array_merge($rtn, $field->getValues());
} else {
$rtn[$fieldName] = $field->getValues();
}
} elseif ($field instanceof Input) {
if ($field->getName()) {
$rtn[$field->getName()] = $field->getValue();
}
}
}
return $rtn;
}
2017-11-05 15:48:36 +01:00
/**
* @param array $values
*/
2016-04-20 17:39:48 +02:00
public function setValues(array $values)
{
2018-01-18 15:51:33 +01:00
foreach ($this->children as $field) {
2016-04-20 17:39:48 +02:00
if ($field instanceof FieldSet) {
$fieldName = $field->getName();
if (empty($fieldName) || !isset($values[$fieldName])) {
$field->setValues($values);
} else {
$field->setValues($values[$fieldName]);
}
} elseif ($field instanceof Input) {
$fieldName = $field->getName();
if (isset($values[$fieldName])) {
$field->setValue($values[$fieldName]);
}
}
}
}
2017-11-05 15:48:36 +01:00
/**
* @param Element $field
*/
2016-04-20 17:39:48 +02:00
public function addField(Element $field)
{
2018-01-18 15:51:33 +01:00
$this->children[$field->getName()] = $field;
2016-04-20 17:39:48 +02:00
$field->setParent($this);
}
2017-11-05 15:48:36 +01:00
/**
* @return boolean
*/
2016-04-20 17:39:48 +02:00
public function validate()
{
$rtn = true;
2018-01-18 15:51:33 +01:00
foreach ($this->children as $child) {
2016-04-20 17:39:48 +02:00
if (!$child->validate()) {
$rtn = false;
}
}
return $rtn;
}
2017-11-05 15:48:36 +01:00
/**
* @param View $view
*/
2017-01-13 16:35:41 +01:00
protected function onPreRender(View &$view)
2016-04-20 17:39:48 +02:00
{
$rendered = [];
2018-01-18 15:51:33 +01:00
foreach ($this->children as $child) {
2016-04-20 17:39:48 +02:00
$rendered[] = $child->render();
}
$view->children = $rendered;
}
2016-04-12 19:31:39 +02:00
2017-11-05 15:48:36 +01:00
/**
* @return Element[]
*/
2016-04-12 19:31:39 +02:00
public function getChildren()
{
2018-01-18 15:51:33 +01:00
return $this->children;
2016-04-12 19:31:39 +02:00
}
2017-11-05 15:48:36 +01:00
/**
* @param string $fieldName
*
* @return Element
*/
2016-04-12 19:31:39 +02:00
public function getChild($fieldName)
{
2018-01-18 15:51:33 +01:00
return $this->children[$fieldName];
2016-04-12 19:31:39 +02:00
}
2016-04-21 19:05:32 +02:00
}