Passed
Push — main ( 2e28d4...91b310 )
by James Ekow Abaka
10:53
created

Container::setErrors()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 6
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 10
rs 10
1
<?php
2
namespace ntentan\honam\engines\php\helpers\form;
3
4
use ntentan\honam\engines\php\Variable;
5
6
/**
7
 * The container class. This abstract class provides the necessary basis for implementing form element containers. The 
8
 * container is a special element which contains other form elements.
9
 */
10
abstract class Container extends Element
11
{
12
    protected $elements = array();
13
14
    /**
15
     * @return string
16
     */
17
    abstract protected function renderHead();
18
19
    /**
20
     * @return string
21
     */
22
    abstract protected function renderFoot();
23
24
    /**
25
     * Method for adding an element to the form container.
26
     * @return Container
27
     */
28
    public function add(Element $element)
29
    {
30
        $this->elements[] = $element;
31
    }
32
33
    /**
34
     * This method sets the data for the fields in this container. The parameter passed to this method is a structured 
35
     * array which has field names as keys and the values as value.
36
     */
37
    public function setData(array|Variable $data)
38
    {
39
        foreach ($this->elements as $element) {
40
            $element->setData($data);
41
        }
42
        return $this;
43
    }
44
45
    public function setErrors(array|Variable $errors): Element
46
    {
47
        foreach($this->elements as $element) {
48
            $fieldNames = array_keys(is_a($errors, Variable::class) ? $errors->unescape() : $errors);
49
            $fieldName = $element->getName();
50
            if (array_search($fieldName, $fieldNames) !== false) {
51
                $element->setErrors($errors[$fieldName]);
52
            }
53
        }
54
        return $this;
55
    }
56
57
    public function render()
58
    {
59
        return $this->renderHead() 
60
            . $this->templateRenderer->render('elements.tpl.php', array('elements' => $this->getElements()))
61
            . $this->renderFoot();
62
    }
63
64
    public function getElements()
65
    {
66
        return $this->elements;
67
    }
68
69
    public function __toString()
70
    {
71
        return $this->render();
72
    }
73
74
    public function isContainer()
75
    {
76
        return true;
77
    }
78
}
79