Completed
Push — master ( 02b993...3405ac )
by Mikołaj
02:38
created

Form::displayAlerts()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace Rudolf\Component\Forms;
4
5
use Rudolf\Component\Alerts;
6
7
abstract class Form
8
{
9
    /**
10
     * @var array
11
     */
12
    protected $data;
13
14
    /**
15
     * @var array
16
     */
17
    protected $fields;
18
19
    public function __construct()
20
    {
21
        $this->validator = new Validator();
0 ignored issues
show
Bug introduced by
The property validator does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
22
    }
23
24
    /**
25
     * Request handler.
26
     *
27
     * @param array $request Request array ($_POST)
28
     */
29
    public function handle(array $request)
30
    {
31
        $this->data = $request;
32
33
        $this->check();
34
    }
35
36
    /**
37
     * Check is any errors.
38
     *
39
     * @return bool
40
     */
41
    public function isValid()
42
    {
43
        return !$this->validator->isErrors();
44
    }
45
46
    /**
47
     * Check is fields values valid.
48
     */
49
    abstract protected function check();
50
51
    /**
52
     * Get data to display in add form.
53
     *
54
     * @param array $mergeWith
55
     *
56
     * @return array
57
     */
58
    public function getDataToDisplay($mergeWith = [])
59
    {
60
        if (empty($this->data)) {
61
            $this->data = [];
62
        }
63
        if (!empty($mergeWith)) {
64
            $this->data = array_merge($mergeWith, $this->data);
65
        }
66
67
        return array_map(function ($a) {
68
            return htmlspecialchars(trim($a));
69
        }, $this->data);
70
    }
71
72
    public function displayAlerts()
73
    {
74
        foreach ($this->validator->getAlerts() as $key => $value) {
75
            Alerts\AlertsCollection::add(new Alerts\Alert(
76
                'error',
77
                $value
78
            ));
79
        }
80
    }
81
}
82