Completed
Push — master ( 127d46...28570c )
by Kristijan
05:49
created

FormField::allDefaults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 7
Bugs 3 Features 4
Metric Value
cc 1
eloc 15
c 7
b 3
f 4
nc 1
nop 0
dl 0
loc 19
ccs 7
cts 7
cp 1
crap 1
rs 9.4285
1
<?php
2
3
namespace Kris\LaravelFormBuilder\Fields;
4
5
use Illuminate\Database\Eloquent\Collection;
6
use Illuminate\Database\Eloquent\Model;
7
use Kris\LaravelFormBuilder\Form;
8
use Kris\LaravelFormBuilder\FormHelper;
9
use Kris\LaravelFormBuilder\RulesParser;
10
11
/**
12
 * Class FormField
13
 *
14
 * @package Kris\LaravelFormBuilder\Fields
15
 */
16
abstract class FormField
17
{
18
    /**
19
     * Name of the field
20
     *
21
     * @var
22
     */
23
    protected $name;
24
25
    /**
26
     * Type of the field
27
     *
28
     * @var
29
     */
30
    protected $type;
31
32
    /**
33
     * All options for the field
34
     *
35
     * @var
36
     */
37
    protected $options = [];
38
39
    /**
40
     * Is field rendered
41
     *
42
     * @var bool
43
     */
44
    protected $rendered = false;
45
46
    /**
47
     * @var Form
48
     */
49
    protected $parent;
50
51
    /**
52
     * @var string
53
     */
54
    protected $template;
55
56
    /**
57
     * @var FormHelper
58
     */
59
    protected $formHelper;
60
61
    /**
62
     * Name of the property for value setting
63
     *
64
     * @var string
65
     */
66
    protected $valueProperty = 'value';
67
68
    /**
69
     * Name of the property for default value
70
     *
71
     * @var string
72
     */
73
    protected $defaultValueProperty = 'default_value';
74
75
    /**
76
     * Is default value set?
77
     * @var bool
78
     */
79
    protected $hasDefault = false;
80
81
    /**
82
     * @var \Closure|null
83
     */
84
    protected $valueClosure = null;
85
86
    /**
87
     * @param             $name
88
     * @param             $type
89
     * @param Form        $parent
90
     * @param array       $options
91
     */
92 70
    public function __construct($name, $type, Form $parent, array $options = [])
93
    {
94 70
        $this->name = $name;
95 70
        $this->type = $type;
96 70
        $this->parent = $parent;
97 70
        $this->formHelper = $this->parent->getFormHelper();
98 70
        $this->setTemplate();
99 70
        $this->setDefaultOptions($options);
100 70
        $this->setupValue();
101 65
    }
102
103 70
    protected function setupValue()
104
    {
105 70
        $value = $this->getOption($this->valueProperty);
106 70
        $isChild = $this->getOption('is_child');
107
108 70
        if ($value instanceof \Closure) {
109
            $this->valueClosure = $value;
110
        }
111
112 70
        if (($value === null || $value instanceof \Closure) && !$isChild) {
113 61
            $this->setValue($this->getModelValueAttribute($this->parent->getModel(), $this->name));
114 18
        } elseif (!$isChild) {
115 12
            $this->hasDefault = true;
116
        }
117 65
    }
118
119
    /**
120
     * Get the template, can be config variable or view path
121
     *
122
     * @return string
123
     */
124
    abstract protected function getTemplate();
125
126
    /**
127
     * @return string
128
     */
129 27
    protected function getViewTemplate()
130
    {
131 27
        return $this->parent->getTemplatePrefix() . $this->getOption('template', $this->template);
132
    }
133
134
    /**
135
     * @param array $options
136
     * @param bool  $showLabel
137
     * @param bool  $showField
138
     * @param bool  $showError
139
     * @return string
140
     */
141 27
    public function render(array $options = [], $showLabel = true, $showField = true, $showError = true)
142
    {
143 27
        $this->prepareOptions($options);
144 27
        $value = $this->getValue();
145 27
        $defaultValue = $this->getDefaultValue();
146
147 27
        if ($showField) {
148 27
            $this->rendered = true;
149
        }
150
151
        // Override default value with value
152 27
        if (!$this->isValidValue($value) && $this->isValidValue($defaultValue)) {
153
            $this->setOption($this->valueProperty, $defaultValue);
154
        }
155
156 27
        if (!$this->needsLabel()) {
157 8
            $showLabel = false;
158
        }
159
160 27
        if ($showError) {
161 26
            $showError = $this->parent->haveErrorsEnabled();
162
        }
163
164 27
        return $this->formHelper->getView()->make(
165 27
            $this->getViewTemplate(),
166
            [
167 27
                'name' => $this->name,
168 27
                'nameKey' => $this->getNameKey(),
169 27
                'type' => $this->type,
170 27
                'options' => $this->options,
171 27
                'showLabel' => $showLabel,
172 27
                'showField' => $showField,
173 27
                'showError' => $showError
174
            ]
175 27
        )->render();
176
    }
177
178
    /**
179
     * Get the attribute value from the model by name
180
     *
181
     * @param mixed $model
182
     * @param string $name
183
     * @return mixed
184
     */
185 63
    protected function getModelValueAttribute($model, $name)
186
    {
187 63
        $transformedName = $this->transformKey($name);
188 63
        if (is_string($model)) {
189
            return $model;
190 63
        } elseif (is_object($model)) {
191 2
            return object_get($model, $transformedName);
192 63
        } elseif (is_array($model)) {
193 62
            return array_get($model, $transformedName);
194
        }
195 5
    }
196
197
    /**
198
     * Transform array like syntax to dot syntax
199
     *
200
     * @param $key
201
     * @return mixed
202
     */
203 70
    protected function transformKey($key)
204
    {
205 70
        return $this->formHelper->transformToDotSyntax($key);
206
    }
207
208
    /**
209
     * Prepare options for rendering
210
     *
211
     * @param array $options
212
     * @return array
213
     */
214 70
    protected function prepareOptions(array $options = [])
215
    {
216 70
        $helper = $this->formHelper;
217 70
        $rulesParser = new RulesParser($this);
218 70
        $rules = $this->getOption('rules');
219 70
        $parsedRules = $rules ? $rulesParser->parse($rules) : [];
220
221 70
        $this->options = $helper->mergeOptions($this->options, $options);
222
223 70
        if ($this->getOption('attr.multiple') && !$this->getOption('tmp.multipleBracesSet')) {
224 2
            $this->name = $this->name.'[]';
225 2
            $this->setOption('tmp.multipleBracesSet', true);
226
        }
227
228 70
        if ($this->parent->haveErrorsEnabled()) {
229 70
            $this->addErrorClass();
230
        }
231
232 70
        if ($this->parent->clientValidationEnabled()) {
233 70
            if ($this->getOption('required') === true || isset($parsedRules['required'])) {
234 3
                $lblClass = $this->getOption('label_attr.class', '');
235 3
                $requiredClass = $helper->getConfig('defaults.required_class', 'required');
236 3
                if (!str_contains($lblClass, $requiredClass)) {
237 3
                    $lblClass .= ' ' . $requiredClass;
238 3
                    $this->setOption('label_attr.class', $lblClass);
239 3
                    $this->setOption('attr.required', 'required');
240
                }
241
            }
242
243 70
            if ($parsedRules) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsedRules of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
244 1
                $attrs = $this->getOption('attr') + $parsedRules;
245 1
                $this->setOption('attr', $attrs);
246
            }
247
        }
248
249 70
        $this->setOption('wrapperAttrs', $helper->prepareAttributes($this->getOption('wrapper')));
250 70
        $this->setOption('errorAttrs', $helper->prepareAttributes($this->getOption('errors')));
251
252 70
        if ($this->getOption('is_child')) {
253 16
            $this->setOption('labelAttrs', $helper->prepareAttributes($this->getOption('label_attr')));
254
        }
255
256 70
        if ($this->getOption('help_block.text')) {
257 1
            $this->setOption(
258 1
                'help_block.helpBlockAttrs',
259 1
                $helper->prepareAttributes($this->getOption('help_block.attr'))
260
            );
261
        }
262
263 70
        return $this->options;
264
    }
265
266
    /**
267
     * Get name of the field
268
     *
269
     * @return string
270
     */
271 23
    public function getName()
272
    {
273 23
        return $this->name;
274
    }
275
276
    /**
277
     * Set name of the field
278
     *
279
     * @param string $name
280
     * @return $this
281
     */
282 11
    public function setName($name)
283
    {
284 11
        $this->name = $name;
285
286 11
        return $this;
287
    }
288
289
    /**
290
     * Get dot notation key for fields
291
     *
292
     * @return string
293
     **/
294 38
    public function getNameKey()
295
    {
296 38
        return $this->transformKey($this->name);
297
    }
298
299
    /**
300
     * Get field options
301
     *
302
     * @return array
303
     */
304 9
    public function getOptions()
305
    {
306 9
        return $this->options;
307
    }
308
309
    /**
310
     * Get single option from options array. Can be used with dot notation ('attr.class')
311
     *
312
     * @param        $option
313
     * @param mixed  $default
314
     *
315
     * @return mixed
316
     */
317 70
    public function getOption($option, $default = null)
318
    {
319 70
        return array_get($this->options, $option, $default);
320
    }
321
322
    /**
323
     * Set field options
324
     *
325
     * @param array $options
326
     * @return $this
327
     */
328 11
    public function setOptions($options)
329
    {
330 11
        $this->options = $this->prepareOptions($options);
331
332 11
        return $this;
333
    }
334
335
    /**
336
     * Set single option on the field
337
     *
338
     * @param string $name
339
     * @param mixed $value
340
     * @return $this
341
     */
342 70
    public function setOption($name, $value)
343
    {
344 70
        array_set($this->options, $name, $value);
345
346 70
        return $this;
347
    }
348
349
    /**
350
     * Get the type of the field
351
     *
352
     * @return string
353
     */
354 40
    public function getType()
355
    {
356 40
        return $this->type;
357
    }
358
359
    /**
360
     * Set type of the field
361
     *
362
     * @param mixed $type
363
     * @return $this
364
     */
365 1
    public function setType($type)
366
    {
367 1
        if ($this->formHelper->getFieldType($type)) {
368 1
            $this->type = $type;
369
        }
370
371 1
        return $this;
372
    }
373
374
    /**
375
     * @return Form
376
     */
377 70
    public function getParent()
378
    {
379 70
        return $this->parent;
380
    }
381
382
    /**
383
     * Check if the field is rendered
384
     *
385
     * @return bool
386
     */
387 4
    public function isRendered()
388
    {
389 4
        return $this->rendered;
390
    }
391
392
    /**
393
     * Default options for field
394
     *
395
     * @return array
396
     */
397 50
    protected function getDefaults()
398
    {
399 50
        return [];
400
    }
401
402
    /**
403
     * Defaults used across all fields
404
     *
405
     * @return array
406
     */
407 70
    private function allDefaults()
408
    {
409
        return [
410 70
            'wrapper' => ['class' => $this->formHelper->getConfig('defaults.wrapper_class')],
411 70
            'attr' => ['class' => $this->formHelper->getConfig('defaults.field_class')],
412 70
            'help_block' => ['text' => null, 'tag' => 'p', 'attr' => [
413 70
                'class' => $this->formHelper->getConfig('defaults.help_block_class')
414
            ]],
415
            'value' => null,
416
            'default_value' => null,
417
            'label' => null,
418
            'label_show' => true,
419
            'is_child' => false,
420 70
            'label_attr' => ['class' => $this->formHelper->getConfig('defaults.label_class')],
421 70
            'errors' => ['class' => $this->formHelper->getConfig('defaults.error_class')],
422
            'rules' => [],
423
            'error_messages' => []
424
        ];
425
    }
426
427
    /**
428
     * Get real name of the field without form namespace
429
     *
430
     * @return string
431
     */
432 69
    public function getRealName()
433
    {
434 69
        return $this->getOption('real_name', $this->name);
435
    }
436
437
    /**
438
     * @param $value
439
     * @return $this
440
     */
441 64
    public function setValue($value)
442
    {
443 64
        if ($this->hasDefault) {
444 1
            return $this;
445
        }
446
447 64
        $closure = $this->valueClosure;
448
449 64
        if ($closure instanceof \Closure) {
450
            $value = $closure($value ?: null);
451
        }
452
453 64
        if (!$this->isValidValue($value)) {
454 62
            $value = $this->getOption($this->defaultValueProperty);
455
        }
456
457 64
        $this->options[$this->valueProperty] = $value;
458
459 64
        return $this;
460
    }
461
462
    /**
463
     * Set the template property on the object
464
     */
465 70
    private function setTemplate()
466
    {
467 70
        $this->template = $this->formHelper->getConfig($this->getTemplate(), $this->getTemplate());
468 70
    }
469
470
    /**
471
     * Add error class to wrapper if validation errors exist
472
     */
473 70
    protected function addErrorClass()
474
    {
475 70
        $errors = $this->parent->getRequest()->session()->get('errors');
476
477 70
        if ($errors && $errors->has($this->getNameKey())) {
478
            $errorClass = $this->formHelper->getConfig('defaults.wrapper_error_class');
479
            $wrapperClass = $this->getOption('wrapper.class');
480
481
            if ($this->getOption('wrapper') && !str_contains($wrapperClass, $errorClass)) {
482
                $wrapperClass .= ' ' . $errorClass;
483
                $this->setOption('wrapper.class', $wrapperClass);
484
            }
485
        }
486 70
    }
487
488
489
    /**
490
     * Merge all defaults with field specific defaults and set template if passed
491
     *
492
     * @param array $options
493
     */
494 70
    protected function setDefaultOptions(array $options = [])
495
    {
496 70
        $this->options = $this->formHelper->mergeOptions($this->allDefaults(), $this->getDefaults());
497 70
        $this->options = $this->prepareOptions($options);
498 70
        $this->setupLabel();
499 70
    }
500
501 70
    protected function setupLabel()
502
    {
503 70
        if ($this->getOption('label') !== null) {
504 17
            return;
505
        }
506
507 68
        if ($langName = $this->parent->getLanguageName()) {
508 4
            $label = sprintf('%s.%s', $langName, $this->getRealName());
509
        } else {
510 65
            $label = $this->getRealName();
511
        }
512
513 68
        $this->setOption('label', $this->formHelper->formatLabel($label));
514 68
    }
515
516
    /**
517
     * Check if fields needs label
518
     *
519
     * @return bool
520
     */
521 27
    protected function needsLabel()
522
    {
523
        // If field is <select> and child of choice, we don't need label for it
524 27
        $isChildSelect = $this->type == 'select' && $this->getOption('is_child') === true;
525
526 27
        if ($this->type == 'hidden' || $isChildSelect) {
527 8
            return false;
528
        }
529
530 24
        return true;
531
    }
532
533
    /**
534
     * Disable field
535
     *
536
     * @return $this
537
     */
538 1
    public function disable()
539
    {
540 1
        $this->setOption('attr.disabled', 'disabled');
541
542 1
        return $this;
543
    }
544
545
    /**
546
     * Enable field
547
     *
548
     * @return $this
549
     */
550 1
    public function enable()
551
    {
552 1
        array_forget($this->options, 'attr.disabled');
553
554 1
        return $this;
555
    }
556
557
    /**
558
     * Get validation rules for a field if any with label for attributes
559
     *
560
     * @return array|null
561
     */
562 3
    public function getValidationRules()
563
    {
564 3
        $rules = $this->getOption('rules', []);
565 3
        $name = $this->getNameKey();
566
567 3
        if (!$rules) {
568
            return [];
569
        }
570
571
        return [
572 3
            'rules' => [$name => $rules],
573 3
            'attributes' => [$name => $this->getOption('label')],
574 3
            'error_messages' => $this->getOption('error_messages', [])
575
        ];
576
    }
577
578
    /**
579
     * Get value property
580
     *
581
     * @param mixed|null $default
582
     * @return mixed
583
     */
584 30
    public function getValue($default = null)
585
    {
586 30
        return $this->getOption($this->valueProperty, $default);
587
    }
588
589
    /**
590
     * Get default value property
591
     *
592
     * @param mixed|null $default
593
     * @return mixed
594
     */
595 27
    public function getDefaultValue($default = null)
596
    {
597 27
        return $this->getOption($this->defaultValueProperty, $default);
598
    }
599
600
    /**
601
     * Check if provided value is valid for this type
602
     *
603
     * @return bool
604
     */
605 65
    protected function isValidValue($value)
606
    {
607 65
        return $value !== null;
608
    }
609
}
610