-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathForm.php
More file actions
54 lines (45 loc) · 1.28 KB
/
Form.php
File metadata and controls
54 lines (45 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
class Form
{
public $values = array();
public $errors = array();
public $fields = array();
public function __construct(array $values, $fields = null)
{
$this->init();
if ($fields) $this->fields = $fields;
$this->values = array_intersect_key($values, $this->fields);
if ($values) {
foreach ($this->fields as $name => $callback) {
try {
call_user_func($callback, $this->get($values, $name));
} catch (DomainException $e) {
$this->errors[$name] = $e->getMessage();
}
}
}
}
protected function init()
{
// initialize $fields when subclassing
}
public static function check($expression, $message)
{
if (false == $expression) {
throw new DomainException($message);
}
}
public function __get($name)
{
return $this->get($this->values, $name);
}
public function error($name, $message = null)
{
$value = $this->get($this->errors, $name);
return $message && $value ? $message : $value;
}
private function get(array $array, $key, $default = null)
{
return isset($array[$key]) ? $array[$key] : $default;
}
}