Passed
Push — master ( 5d6601...391c2f )
by Gabor
04:19
created

HtmlFormElement::setName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2.0078

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 7
cts 8
cp 0.875
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
crap 2.0078
1
<?php
2
/**
3
 * WebHemi.
4
 *
5
 * PHP version 7.1
6
 *
7
 * @copyright 2012 - 2017 Gixx-web (http://www.gixx-web.com)
8
 * @license   https://opensource.org/licenses/MIT The MIT License (MIT)
9
 *
10
 * @link      http://www.gixx-web.com
11
 */
12
declare(strict_types = 1);
13
14
namespace WebHemi\Form\Html;
15
16
use InvalidArgumentException;
17
use WebHemi\Form\FormElementInterface;
18
use WebHemi\Traits\CamelCaseToUnderScoreTrait;
19
use WebHemi\Validator\ValidatorInterface;
20
21
/**
22
 * Class HtmlFormElement
23
 */
24
class HtmlFormElement implements FormElementInterface
25
{
26
    public const HTML_ELEMENT_BUTTON = 'button';
27
    public const HTML_ELEMENT_FORM = 'form';
28
    public const HTML_ELEMENT_INPUT_CHECKBOX = 'checkbox';
29
    public const HTML_ELEMENT_INPUT_FILE = 'file';
30
    public const HTML_ELEMENT_INPUT_HIDDEN = 'hidden';
31
    public const HTML_ELEMENT_INPUT_IMAGE = 'IMAGE';
32
    public const HTML_ELEMENT_INPUT_PASSWORD = 'password';
33
    public const HTML_ELEMENT_INPUT_RADIO = 'radio';
34
    public const HTML_ELEMENT_INPUT_RESET = 'reset';
35
    public const HTML_ELEMENT_INPUT_SUBMIT = 'submit';
36
    public const HTML_ELEMENT_INPUT_TEXT = 'text';
37
    public const HTML_ELEMENT_SELECT = 'select';
38
    public const HTML_ELEMENT_TEXTAREA = 'textarea';
39
40
    /** @var string */
41
    private $name;
42
    /** @var string */
43
    private $id;
44
    /** @var string */
45
    private $label;
46
    /** @var string */
47
    private $type;
48
    /** @var array */
49
    private $values = [];
50
    /** @var array */
51
    private $valueRange = [];
52
    /** @var array<ValidatorInterface> */
53
    private $validators = [];
54
    /** @var array */
55
    private $errors = [];
56
    /** @var array */
57
    protected $validTypes = [
58
        self::HTML_ELEMENT_BUTTON,
59
        self::HTML_ELEMENT_FORM,
60
        self::HTML_ELEMENT_INPUT_CHECKBOX,
61
        self::HTML_ELEMENT_INPUT_FILE,
62
        self::HTML_ELEMENT_INPUT_HIDDEN,
63
        self::HTML_ELEMENT_INPUT_IMAGE,
64
        self::HTML_ELEMENT_INPUT_PASSWORD,
65
        self::HTML_ELEMENT_INPUT_RADIO,
66
        self::HTML_ELEMENT_INPUT_RESET,
67
        self::HTML_ELEMENT_INPUT_SUBMIT,
68
        self::HTML_ELEMENT_INPUT_TEXT,
69
        self::HTML_ELEMENT_SELECT,
70
        self::HTML_ELEMENT_TEXTAREA,
71
    ];
72
73
    /**
74
     * Converts CamelCase text to under_score equivalent.
75
     * Converts any text to Identifier-like string
76
     */
77
    use CamelCaseToUnderScoreTrait;
78
79
    /**
80
     * HtmlFormElement constructor.
81
     *
82
     * @param string $type       The type of the form element.
83
     * @param string $name       For HTML forms it is the name attribute.
84
     * @param string $label      Optional. The label of the element. If not set the $name should be used.
85
     * @param array  $values     Optional. The values of the element.
86
     * @param array  $valueRange Optional. The range of interpretation.
87
     */
88 1
    public function __construct(
89
        string $type,
90
        string $name,
91
        string $label = null,
92
        array $values = [],
93
        array $valueRange = []
94
    ) {
95 1
        if (!in_array($type, $this->validTypes)) {
96
            throw new InvalidArgumentException(
97
                sprintf(
98
                    'The given type "%s" is not a valid %s type.',
99
                    $type,
100
                    __CLASS__
101
                ),
102
                1001
103
            );
104
        }
105
106 1
        $this->setName($name);
107
108 1
        $this->type = $type;
109 1
        $this->label = $label;
110 1
        $this->values = $values;
111 1
        $this->valueRange = $valueRange;
112 1
    }
113
114
    /**
115
     * Sets element's name.
116
     *
117
     * @param string $name
118
     * @throws InvalidArgumentException
119
     * @return FormElementInterface
120
     */
121 1
    public function setName(string $name) : FormElementInterface
122
    {
123 1
        if (empty($name)) {
124
            throw new InvalidArgumentException('During conversion the argument value become an empty string!', 1002);
125
        }
126
127 1
        $this->name = $name;
128
129 1
        $name = $this->camelCaseToUnderscore($name);
130 1
        $name = preg_replace('/[^a-zA-Z0-9]/', '_', $name);
131 1
        $this->id = trim(str_replace('__', '_', $name), '_');
132
133 1
        return $this;
134
    }
135
136
    /**
137
     * Gets the element's name.
138
     *
139
     * @return string
140
     */
141 1
    public function getName() : string
142
    {
143 1
        return $this->name;
144
    }
145
146
    /**
147
     * Gets the element's name.
148
     *
149
     * @return string
150
     */
151
    public function getId() : string
152
    {
153
        return $this->id;
154
    }
155
156
    /**
157
     * Gets the element's type.
158
     *
159
     * @return string
160
     */
161
    public function getType() : string
162
    {
163
        return $this->type;
164
    }
165
166
    /**
167
     * Sets the element's label.
168
     *
169
     * @param string $label
170
     * @return FormElementInterface
171
     */
172
    public function setLabel(string $label) : FormElementInterface
173
    {
174
        $this->label = $label;
175
176
        return $this;
177
    }
178
179
    /**
180
     * Gets the element's label.
181
     *
182
     * @return string
183
     */
184
    public function getLabel() : string
185
    {
186
        return $this->label ?? $this->name;
187
    }
188
189
    /**
190
     * Sets the values.
191
     *
192
     * @param array $values
193
     * @return FormElementInterface
194
     */
195 1
    public function setValues(array $values) : FormElementInterface
196
    {
197 1
        $this->values = $values;
198
199 1
        return $this;
200
    }
201
202
    /**
203
     * Gets the values.
204
     *
205
     * @return array
206
     */
207 1
    public function getValues() : array
208
    {
209 1
        return $this->values;
210
    }
211
212
    /**
213
     * Sets the range of interpretation. Depends on the element type how it is used: exact element list or a min/max.
214
     *
215
     * @param array $valueRange
216
     * @return FormElementInterface
217
     */
218
    public function setValueRange(array $valueRange) : FormElementInterface
219
    {
220
        $this->valueRange = $valueRange;
221
222
        return $this;
223
    }
224
225
    /**
226
     * Get the range of interpretation.
227
     *
228
     * @return array
229
     */
230
    public function getValueRange() : array
231
    {
232
        return $this->valueRange;
233
    }
234
235
    /**
236
     * Adds a validator to the element.
237
     *
238
     * @param ValidatorInterface $validator
239
     * @return FormElementInterface
240
     */
241
    public function addValidator(ValidatorInterface $validator) : FormElementInterface
242
    {
243
        $this->validators[] = $validator;
244
245
        return $this;
246
    }
247
248
    /**
249
     * Validates the element.
250
     *
251
     * @return FormElementInterface
252
     */
253
    public function validate() : FormElementInterface
254
    {
255
        $result = [];
256
257
        /** @var ValidatorInterface $validator */
258
        foreach ($this->validators as $validator) {
259
            if (!$validator->validate($this->values)) {
260
                $result[get_class($validator)] = $validator->getErrors();
261
            }
262
        }
263
264
        return $this;
265
    }
266
267
    /**
268
     * Returns the errors collected during the validation.
269
     *
270
     * @return array
271
     */
272
    public function getErrors() : array
273
    {
274
        return $this->errors;
275
    }
276
}
277