Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.97% covered (success)
95.97%
143 / 149
50.00% covered (warning)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
Fields
95.97% covered (success)
95.97%
143 / 149
50.00% covered (warning)
50.00%
1 / 2
90
0.00% covered (danger)
0.00%
0 / 1
 create
94.55% covered (success)
94.55%
104 / 110
0.00% covered (danger)
0.00%
0 / 1
64.66
 getConfigFromTable
100.00% covered (success)
100.00%
39 / 39
100.00% covered (success)
100.00%
1 / 1
26
1<?php
2/**
3 * Pop PHP Framework (http://www.popphp.org/)
4 *
5 * @link       https://github.com/popphp/popphp-framework
6 * @author     Nick Sagona, III <dev@nolainteractive.com>
7 * @copyright  Copyright (c) 2009-2023 NOLA Interactive, LLC. (http://www.nolainteractive.com)
8 * @license    http://www.popphp.org/license     New BSD License
9 */
10
11/**
12 * @namespace
13 */
14namespace Pop\Form;
15
16/**
17 * Form fields config class
18 *
19 * @category   Pop
20 * @package    Pop\Form
21 * @author     Nick Sagona, III <dev@nolainteractive.com>
22 * @copyright  Copyright (c) 2009-2023 NOLA Interactive, LLC. (http://www.nolainteractive.com)
23 * @license    http://www.popphp.org/license     New BSD License
24 * @version    3.6.0
25 */
26class Fields
27{
28
29    /**
30     * Static factory method to create a field element object from a field config array
31     *
32     * @param  string $name
33     * @param  array  $field
34     * @throws Exception
35     * @return Element\AbstractElement
36     */
37    public static function create($name, array $field)
38    {
39        if (!isset($field['type'])) {
40            throw new Exception('Error: The field type was not set.');
41        }
42
43        $type         = $field['type'];
44        $value        = (isset($field['value']))      ? $field['value']      : null;
45        $values       = (isset($field['values']))     ? $field['values']     : [];
46        $label        = (isset($field['label']))      ? $field['label']      : null;
47        $indent       = (isset($field['indent']))     ? $field['indent']     : null;
48        $checked      = (isset($field['checked']))    ? $field['checked']    : null;
49        $selected     = (isset($field['selected']))   ? $field['selected']   : null;
50        $required     = (isset($field['required']))   ? $field['required']   : null;
51        $disabled     = (isset($field['disabled']))   ? $field['disabled']   : null;
52        $readonly     = (isset($field['readonly']))   ? $field['readonly']   : null;
53        $attributes   = (isset($field['attributes'])) ? $field['attributes'] : null;
54        $validators   = (isset($field['validators'])) ? $field['validators'] : null;
55        $render       = (isset($field['render']))     ? $field['render']     : false;
56        $expire       = (isset($field['expire']))     ? $field['expire']     : 300;
57        $captcha      = (isset($field['captcha']))    ? $field['captcha']    : null;
58        $answer       = (isset($field['answer']))     ? $field['answer']     : null;
59        $min          = (isset($field['min']))        ? $field['min']        : false;
60        $max          = (isset($field['max']))        ? $field['max']        : false;
61        $xmlFile      = (isset($field['xml']))        ? $field['xml']        : null;
62        $hint         = (isset($field['hint']))       ? $field['hint']       : null;
63        $hintAttribs  = (isset($field['hint-attributes'])) ? $field['hint-attributes']   : null;
64        $labelAttribs = (isset($field['label-attributes'])) ? $field['label-attributes'] : null;
65
66        $errorPre = (isset($field['error']) && ($field['error'] == 'pre'));
67
68        // Initialize the form element.
69        switch (strtolower($type)) {
70            case 'button':
71                $element = new Element\Button($name, $value, $indent);
72                break;
73            case 'select':
74                $element = new Element\Select($name, $values, $selected, $xmlFile, $indent);
75                break;
76            case 'select-multiple':
77                $element = new Element\SelectMultiple($name, $values, $selected, $xmlFile, $indent);
78                break;
79            case 'textarea':
80                $element = new Element\Textarea($name, $value, $indent);
81                break;
82            case 'checkbox':
83                $element = new Element\Input\Checkbox($name, $value, $indent);
84                if (($checked === true) || ($value == $checked)) {
85                    $element->check();
86                }
87                break;
88            case 'checkbox-set':
89                $element = new Element\CheckboxSet($name, $values, $checked, $indent);
90                break;
91            case 'radio':
92                $element = new Element\Input\Radio($name, $value, $indent);
93                if (($checked === true) || ($value == $checked)) {
94                    $element->check();
95                }
96                break;
97            case 'radio-set':
98                $element = new Element\RadioSet($name, $values, $checked, $indent);
99                break;
100            case 'csrf':
101                $element = new Element\Input\Csrf($name, $value, $expire, $indent);
102                break;
103            case 'captcha':
104                $element = new Element\Input\Captcha($name, $value, $captcha, $answer, $expire, $indent);
105                break;
106            case 'input-button':
107                $element = new Element\Input\Button($name, $value);
108                break;
109            case 'datalist':
110                $element = new Element\Input\Datalist($name, $values, $value);
111                break;
112            case 'datetime':
113                $element = new Element\Input\DateTime($name, $value);
114                break;
115            case 'datetime-local':
116                $element = new Element\Input\DateTimeLocal($name, $value);
117                break;
118            case 'number':
119                $element = new Element\Input\Number($name, $min, $max, $value);
120                break;
121            case 'range':
122                $element = new Element\Input\Range($name, $min, $max, $value);
123                break;
124            default:
125                $class = 'Pop\\Form\\Element\\Input\\' . ucfirst(strtolower($type));
126                if (!class_exists($class)) {
127                    throw new Exception('Error: That class for that form element (' . $type . ') does not exist.');
128                }
129                $element = new $class($name, $value);
130                if ($class == 'Pop\\Form\\Element\\Input\\Password') {
131                    $element->setRenderValue($render);
132                }
133        }
134
135        // Set the label.
136        if (null !== $label) {
137            $element->setLabel($label);
138        }
139        // Set the label attributes.
140        if ((null !== $labelAttribs) && is_array($labelAttribs)) {
141            $element->setLabelAttributes($labelAttribs);
142        }
143        // Set the hint.
144        if (null !== $hint) {
145            $element->setHint($hint);
146        }
147        // Set the hint attributes.
148        if ((null !== $hintAttribs) && is_array($hintAttribs)) {
149            $element->setHintAttributes($hintAttribs);
150        }
151        // Set if required.
152        if ((null !== $required) && ($required)) {
153            $element->setRequired($required);
154        }
155        // Set if disabled.
156        if ((null !== $disabled) && ($disabled)) {
157            $element->setDisabled($disabled);
158        }
159        // Set if readonly.
160        if ((null !== $readonly) && ($readonly)) {
161            $element->setReadonly($readonly);
162        }
163
164        $element->setErrorPre($errorPre);
165
166        // Set any attributes.
167        if (null !== $attributes) {
168            if ($element instanceof Element\CheckboxSet) {
169                $element->setCheckboxAttributes($attributes);
170            } else if ($element instanceof Element\RadioSet) {
171                $element->setRadioAttributes($attributes);
172            } else {
173                $element->setAttributes($attributes);
174            }
175        }
176        // Set any validators.
177        if (null !== $validators) {
178            if (is_array($validators)) {
179                $element->addValidators($validators);
180            } else {
181                $element->addValidator($validators);
182            }
183        }
184
185        return $element;
186    }
187
188    /**
189     * Static factory method to get field configs from a database table
190     *
191     * @param  array $tableInfo
192     * @param  array $attribs
193     * @param  array $config
194     * @param  mixed $omit
195     * @throws Exception
196     * @return array
197     */
198    public static function getConfigFromTable(array $tableInfo, array $attribs = null, array $config = null, $omit = null)
199    {
200        $fields = [];
201
202        if (!isset($tableInfo['tableName']) || !isset($tableInfo['columns'])) {
203            throw new Exception('Error: The table info parameter is not in the correct format');
204        }
205
206        if (null !== $omit) {
207            if (!is_array($omit)) {
208                $omit = [$omit];
209            }
210        } else {
211            $omit = [];
212        }
213
214        if (null === $config) {
215            $config = [];
216        }
217
218        foreach ($tableInfo['columns'] as $name => $value) {
219            if (!in_array($name, $omit)) {
220                $fieldValue = null;
221                $fieldLabel = null;
222                $attributes = null;
223
224                if (isset($config[$name]) && isset($config[$name]['validators'])) {
225                    $validators = (!is_array($config[$name]['validators'])) ?
226                        [$config[$name]['validators']] : $config[$name]['validators'];
227                } else {
228                    $validators = null;
229                }
230
231                if (isset($config[$name]) && isset($config[$name]['type'])) {
232                    $fieldType = $config[$name]['type'];
233                } else if (stripos($name, 'password') !== false) {
234                    $fieldType = 'password';
235                } else if ((stripos($name, 'email') !== false) || (stripos($name, 'e-mail') !== false) ||
236                    (stripos($name, 'e_mail') !== false)) {
237                    $fieldType = 'email';
238                    if (null !== $validators) {
239                        $validators[] = new \Pop\Validator\Email();
240                    } else {
241                        $validators = [new \Pop\Validator\Email()];
242                    }
243                } else {
244                    $fieldType = (stripos($value['type'], 'text') !== false) ? 'textarea' : 'text';
245                }
246
247                $fieldValue = (isset($config[$name]) && isset($config[$name]['value'])) ? $config[$name]['value'] : null;
248
249                if ($fieldType != 'hidden') {
250                    $fieldLabel = ucwords(str_replace('_', ' ', $name)) . ':';
251                }
252
253                if (null !== $attribs) {
254                    if (isset($attribs[$fieldType])) {
255                        $attributes =  $attribs[$fieldType];
256                    }
257                }
258
259                $required = (isset($config[$name]) && isset($config[$name]['required'])) ?
260                    (bool)$config[$name]['required'] : !($value['null']);
261
262                $fields[$name] = [
263                    'type'       => $fieldType,
264                    'label'      => $fieldLabel,
265                    'value'      => $fieldValue,
266                    'required'   => $required,
267                    'attributes' => $attributes,
268                    'validators' => $validators
269                ];
270            }
271        }
272
273        return $fields;
274    }
275
276}