/
Text.php
76 lines (65 loc) · 2.28 KB
/
Text.php
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Useful;
use Nibble\NibbleForms\Field;
class Text extends Field
{
protected $label,
$content = '/.*/',
$attribute_string = '',
$class = '',
$required = true;
public $error = array(),
$field_type = 'text';
public function __construct($label, $attributes = array())
{
$this->label = $label;
if (isset($attributes['required'])) {
$this->required = $attributes['required'];
} else {
$attributes['required'] = true;
}
if (isset($attributes['content'])) {
$this->content = $attributes['content'];
}
$this->attributes = $attributes;
}
public function attributeString()
{
if (!empty($this->error)) {
$this->class = 'error';
}
$this->attribute_string = '';
foreach ($this->attributes as $attribute => $val) {
if ($attribute == 'class') {
$this->class.= ' ' . $val;
} else {
$this->attribute_string .= $val ? ' ' . ($val === true ? $attribute : "$attribute=\"$val\"") : '';
}
}
}
public function returnField($form_name, $name, $value = '')
{
$this->attributeString();
return array(
'messages' => !empty($this->custom_error) && !empty($this->error) ? $this->custom_error : $this->error,
'label' => $this->label === false ? false : sprintf('<label for="%s_%s" class="%s">%s</label>', $form_name, $name, $this->class, $this->label),
'field' => sprintf('<input type="%1$s" name="%6$s[%2$s]" id="%6$s_%2$s" value="%3$s" %4$s class="%5$s" />', $this->field_type, $name, $value, $this->attribute_string, $this->class, $form_name),
'html' => $this->html
);
}
public function validate($val)
{
if ($this->required) {
if (Useful::stripper($val) === false) {
$this->error[] = 'is required';
}
}
if (Useful::stripper($val) !== false) {
if (!preg_match($this->content, $val)) {
$this->error[] = 'is not valid';
}
}
return !empty($this->error) ? false : true;
}
}