Passed
Push — master ( 6ffe60...39863f )
by Radu
01:28
created

AbstractForm::isSent()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 4
nop 0
1
<?php
2
namespace WebServCo\Framework;
3
4
abstract class AbstractForm extends \WebServCo\Framework\AbstractLibrary
5
{
6
    protected $errors;
7
8
    protected $filtered;
9
10
    protected $submitFields;
11
12
    protected $valid;
13
14
    use \WebServCo\Framework\Traits\ExposeLibrariesTrait;
15
16
    public function __construct($settings, $defaultData = [], $submitFields = [])
17
    {
18
        parent::__construct($settings);
19
20
        /**
21
         * Set form data
22
         */
23
        foreach ($this->setting('meta', []) as $field => $title) {
24
            $this->setData(
25
                $field,
26
                $this->request()->data( // from POST
27
                    $field,
28
                    \WebServCo\Framework\Utils::arrayKey($field, $defaultData, null) // default data
29
                )
30
            );
31
        }
32
33
        $this->errors = [];
34
35
        $this->filtered = $this->filter();
36
37
        $this->submitFields = $submitFields;
38
39
        if ($this->isSent()) {
40
            $this->valid = $this->validate();
41
        }
42
    }
43
44
    abstract protected function db();
45
46
    /**
47
     * @return bool
48
     */
49
    abstract protected function filter();
50
51
    /**
52
     * @return bool
53
     */
54
    abstract protected function validate();
55
56
    final public function isSent()
57
    {
58
        if (!empty($this->submitFields)) {
59
            foreach ($this->submitFields as $field) {
60
                if ($this->request()->data($field)) {
61
                    return true;
62
                }
63
            }
64
        } else {
65
            return $this->request()->getMethod() === \WebServCo\Framework\Http::METHOD_POST;
66
        }
67
    }
68
69
    final public function isValid()
70
    {
71
        return $this->valid;
72
    }
73
74
    final public function clear()
75
    {
76
        $this->data = [];
77
        $this->filtered = [];
78
        $this->errors = [];
79
    }
80
81
    final public function toArray()
82
    {
83
        return [
84
            'meta' => $this->setting('meta', []),
85
            'help' => $this->setting('help', []),
86
            'required' => array_fill_keys($this->setting('required', []), true),
87
            'data' => $this->data,
88
            'errors' => $this->errors,
89
        ];
90
    }
91
}
92