Completed
Push — master ( 5e6e0b...ac11c6 )
by Kristijan
05:33
created

FormField::getOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
namespace Kris\LaravelFormBuilder\Fields;
4
5
use Kris\LaravelFormBuilder\Form;
6
use Illuminate\Database\Eloquent\Model;
7
use Kris\LaravelFormBuilder\FormHelper;
8
use Kris\LaravelFormBuilder\RulesParser;
9
use Illuminate\Database\Eloquent\Collection;
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 81
    public function __construct($name, $type, Form $parent, array $options = [])
93
    {
94 81
        $this->name = $name;
95 81
        $this->type = $type;
96 81
        $this->parent = $parent;
97 81
        $this->formHelper = $this->parent->getFormHelper();
98 81
        $this->setTemplate();
99 81
        $this->setDefaultOptions($options);
100 81
        $this->setupValue();
101 76
    }
102
103 81
    protected function setupValue()
104
    {
105 81
        $value = $this->getOption($this->valueProperty);
106 81
        $isChild = $this->getOption('is_child');
107
108 81
        if ($value instanceof \Closure) {
109
            $this->valueClosure = $value;
110
        }
111
112 81
        if (($value === null || $value instanceof \Closure) && !$isChild) {
113 72
            $this->setValue($this->getModelValueAttribute($this->parent->getModel(), $this->name));
114 18
        } elseif (!$isChild) {
115 12
            $this->hasDefault = true;
116
        }
117 76
    }
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 31
    protected function getViewTemplate()
130
    {
131 31
        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 31
    public function render(array $options = [], $showLabel = true, $showField = true, $showError = true)
142
    {
143 31
        $this->prepareOptions($options);
144 31
        $value = $this->getValue();
145 31
        $defaultValue = $this->getDefaultValue();
146
147 31
        if ($showField) {
148 31
            $this->rendered = true;
149
        }
150
151
        // Override default value with value
152 31
        if (!$this->isValidValue($value) && $this->isValidValue($defaultValue)) {
153
            $this->setOption($this->valueProperty, $defaultValue);
154
        }
155
156 31
        if (!$this->needsLabel()) {
157 9
            $showLabel = false;
158
        }
159
160 31
        if ($showError) {
161 30
            $showError = $this->parent->haveErrorsEnabled();
162
        }
163
164 31
        return $this->formHelper->getView()->make(
165 31
            $this->getViewTemplate(),
166
            [
167 31
                'name' => $this->name,
168 31
                'nameKey' => $this->getNameKey(),
169 31
                'type' => $this->type,
170 31
                'options' => $this->options,
171 31
                'showLabel' => $showLabel,
172 31
                'showField' => $showField,
173 31
                'showError' => $showError
174
            ]
175 31
        )->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 74
    protected function getModelValueAttribute($model, $name)
186
    {
187 74
        $transformedName = $this->transformKey($name);
188 74
        if (is_string($model)) {
189
            return $model;
190 74
        } elseif (is_object($model)) {
191 2
            return object_get($model, $transformedName);
192 74
        } elseif (is_array($model)) {
193 73
            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 81
    protected function transformKey($key)
204
    {
205 81
        return $this->formHelper->transformToDotSyntax($key);
206
    }
207
208
    /**
209
     * Prepare options for rendering
210
     *
211
     * @param array $options
212
     * @return array
213
     */
214 81
    protected function prepareOptions(array $options = [])
215
    {
216 81
        $helper = $this->formHelper;
217 81
        $rulesParser = new RulesParser($this);
218 81
        $rules = $this->getOption('rules');
219 81
        $parsedRules = $rules ? $rulesParser->parse($rules) : [];
220
221 81
        $this->options = $helper->mergeOptions($this->options, $options);
222
223 81
        foreach (['attr', 'label_attr', 'wrapper'] as $appendable) {
224
            // Append values to the 'class' attribute
225 81
            if ($this->getOption("{$appendable}.class_append")) {
226
                // Combine the current class attribute with the appends
227 3
                $append = $this->getOption("{$appendable}.class_append");
228 3
                $classAttribute = $this->getOption("{$appendable}.class", '').' '.$append;
229 3
                $this->setOption("{$appendable}.class", $classAttribute);
230
231
                // Then remove the class_append option to prevent it from showing up as an attribute in the HTML
232 81
                $this->setOption("{$appendable}.class_append", null);
233
            }
234
        }
235
236 81
        if ($this->getOption('attr.multiple') && !$this->getOption('tmp.multipleBracesSet')) {
237 2
            $this->name = $this->name.'[]';
238 2
            $this->setOption('tmp.multipleBracesSet', true);
239
        }
240
241 81
        if ($this->parent->haveErrorsEnabled()) {
242 81
            $this->addErrorClass();
243
        }
244
245 81
        if ($this->getOption('required') === true || isset($parsedRules['required'])) {
246 4
            $lblClass = $this->getOption('label_attr.class', '');
247 4
            $requiredClass = $helper->getConfig('defaults.required_class', 'required');
248
249 4
            if (! str_contains($lblClass, $requiredClass)) {
250 4
                $lblClass .= ' '.$requiredClass;
251 4
                $this->setOption('label_attr.class', $lblClass);
252
            }
253
254 4
            if ($this->parent->clientValidationEnabled()) {
255 3
                $this->setOption('attr.required', 'required');
256
257 3
                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...
258 1
                    $attrs = $this->getOption('attr') + $parsedRules;
259 1
                    $this->setOption('attr', $attrs);
260
                }
261
            }
262
        }
263
264 81
        $this->setOption('wrapperAttrs', $helper->prepareAttributes($this->getOption('wrapper')));
265 81
        $this->setOption('errorAttrs', $helper->prepareAttributes($this->getOption('errors')));
266
267 81
        if ($this->getOption('is_child')) {
268 16
            $this->setOption('labelAttrs', $helper->prepareAttributes($this->getOption('label_attr')));
269
        }
270
271 81
        if ($this->getOption('help_block.text')) {
272 1
            $this->setOption(
273 1
                'help_block.helpBlockAttrs',
274 1
                $helper->prepareAttributes($this->getOption('help_block.attr'))
275
            );
276
        }
277
278 81
        return $this->options;
279
    }
280
281
    /**
282
     * Get name of the field
283
     *
284
     * @return string
285
     */
286 24
    public function getName()
287
    {
288 24
        return $this->name;
289
    }
290
291
    /**
292
     * Set name of the field
293
     *
294
     * @param string $name
295
     * @return $this
296
     */
297 11
    public function setName($name)
298
    {
299 11
        $this->name = $name;
300
301 11
        return $this;
302
    }
303
304
    /**
305
     * Get dot notation key for fields
306
     *
307
     * @return string
308
     **/
309 47
    public function getNameKey()
310
    {
311 47
        return $this->transformKey($this->name);
312
    }
313
314
    /**
315
     * Get field options
316
     *
317
     * @return array
318
     */
319 12
    public function getOptions()
320
    {
321 12
        return $this->options;
322
    }
323
324
    /**
325
     * Get single option from options array. Can be used with dot notation ('attr.class')
326
     *
327
     * @param        $option
328
     * @param mixed  $default
329
     *
330
     * @return mixed
331
     */
332 81
    public function getOption($option, $default = null)
333
    {
334 81
        return array_get($this->options, $option, $default);
335
    }
336
337
    /**
338
     * Set field options
339
     *
340
     * @param array $options
341
     * @return $this
342
     */
343 11
    public function setOptions($options)
344
    {
345 11
        $this->options = $this->prepareOptions($options);
346
347 11
        return $this;
348
    }
349
350
    /**
351
     * Set single option on the field
352
     *
353
     * @param string $name
354
     * @param mixed $value
355
     * @return $this
356
     */
357 81
    public function setOption($name, $value)
358
    {
359 81
        array_set($this->options, $name, $value);
360
361 81
        return $this;
362
    }
363
364
    /**
365
     * Get the type of the field
366
     *
367
     * @return string
368
     */
369 48
    public function getType()
370
    {
371 48
        return $this->type;
372
    }
373
374
    /**
375
     * Set type of the field
376
     *
377
     * @param mixed $type
378
     * @return $this
379
     */
380 1
    public function setType($type)
381
    {
382 1
        if ($this->formHelper->getFieldType($type)) {
383 1
            $this->type = $type;
384
        }
385
386 1
        return $this;
387
    }
388
389
    /**
390
     * @return Form
391
     */
392 81
    public function getParent()
393
    {
394 81
        return $this->parent;
395
    }
396
397
    /**
398
     * Check if the field is rendered
399
     *
400
     * @return bool
401
     */
402 4
    public function isRendered()
403
    {
404 4
        return $this->rendered;
405
    }
406
407
    /**
408
     * Default options for field
409
     *
410
     * @return array
411
     */
412 61
    protected function getDefaults()
413
    {
414 61
        return [];
415
    }
416
417
    /**
418
     * Defaults used across all fields
419
     *
420
     * @return array
421
     */
422 81
    private function allDefaults()
423
    {
424
        return [
425 81
            'wrapper' => ['class' => $this->formHelper->getConfig('defaults.wrapper_class')],
426 81
            'attr' => ['class' => $this->formHelper->getConfig('defaults.field_class')],
427 81
            'help_block' => ['text' => null, 'tag' => 'p', 'attr' => [
428 81
                'class' => $this->formHelper->getConfig('defaults.help_block_class')
429
            ]],
430
            'value' => null,
431
            'default_value' => null,
432
            'label' => null,
433
            'label_show' => true,
434
            'is_child' => false,
435 81
            'label_attr' => ['class' => $this->formHelper->getConfig('defaults.label_class')],
436 81
            'errors' => ['class' => $this->formHelper->getConfig('defaults.error_class')],
437
            'rules' => [],
438
            'error_messages' => []
439
        ];
440
    }
441
442
    /**
443
     * Get real name of the field without form namespace
444
     *
445
     * @return string
446
     */
447 80
    public function getRealName()
448
    {
449 80
        return $this->getOption('real_name', $this->name);
450
    }
451
452
    /**
453
     * @param $value
454
     * @return $this
455
     */
456 75
    public function setValue($value)
457
    {
458 75
        if ($this->hasDefault) {
459 1
            return $this;
460
        }
461
462 75
        $closure = $this->valueClosure;
463
464 75
        if ($closure instanceof \Closure) {
465
            $value = $closure($value ?: null);
466
        }
467
468 75
        if (!$this->isValidValue($value)) {
469 73
            $value = $this->getOption($this->defaultValueProperty);
470
        }
471
472 75
        $this->options[$this->valueProperty] = $value;
473
474 75
        return $this;
475
    }
476
477
    /**
478
     * Set the template property on the object
479
     */
480 81
    private function setTemplate()
481
    {
482 81
        $this->template = $this->formHelper->getConfig($this->getTemplate(), $this->getTemplate());
483 81
    }
484
485
    /**
486
     * Add error class to wrapper if validation errors exist
487
     */
488 81
    protected function addErrorClass()
489
    {
490 81
        $errors = $this->parent->getRequest()->session()->get('errors');
491
492 81
        if ($errors && $errors->has($this->getNameKey())) {
493
            $errorClass = $this->formHelper->getConfig('defaults.wrapper_error_class');
494
            $wrapperClass = $this->getOption('wrapper.class');
495
496
            if ($this->getOption('wrapper') && !str_contains($wrapperClass, $errorClass)) {
497
                $wrapperClass .= ' ' . $errorClass;
498
                $this->setOption('wrapper.class', $wrapperClass);
499
            }
500
        }
501 81
    }
502
503
504
    /**
505
     * Merge all defaults with field specific defaults and set template if passed
506
     *
507
     * @param array $options
508
     */
509 81
    protected function setDefaultOptions(array $options = [])
510
    {
511 81
        $this->options = $this->formHelper->mergeOptions($this->allDefaults(), $this->getDefaults());
512 81
        $this->options = $this->prepareOptions($options);
513
514 81
        $defaults = $this->setDefaultClasses($options);
515 81
        $this->options = $this->formHelper->mergeOptions($this->options, $defaults);
516
517 81
        $this->setupLabel();
518 81
    }
519
520
    /**
521
     * Creates default wrapper classes for the form element.
522
     *
523
     * @param array $options
524
     * @return array
525
     */
526 81
    protected function setDefaultClasses(array $options = [])
527
    {
528 81
        $wrapper_class = $this->formHelper->getConfig('defaults.' . $this->type . '.wrapper_class', '');
529 81
        $label_class = $this->formHelper->getConfig('defaults.' . $this->type . '.label_class', '');
530 81
        $field_class = $this->formHelper->getConfig('defaults.' . $this->type . '.field_class', '');
531
532 81
        $defaults = [];
533 81
        if ($wrapper_class) {
534
            $defaults['wrapper']['class'] = $wrapper_class;
535
        }
536 81
        if ($label_class) {
537
            $defaults['label_attr']['class'] = $label_class;
538
        }
539 81
        if ($field_class) {
540
            $defaults['attr']['class'] = $field_class;
541
        }
542 81
        return $defaults;
543
    }
544
545 81
    protected function setupLabel()
546
    {
547 81
        if ($this->getOption('label') !== null) {
548 20
            return;
549
        }
550
551 79
        if ($langName = $this->parent->getLanguageName()) {
552 4
            $label = sprintf('%s.%s', $langName, $this->getRealName());
553
        } else {
554 76
            $label = $this->getRealName();
555
        }
556
557 79
        $this->setOption('label', $this->formHelper->formatLabel($label));
558 79
    }
559
560
    /**
561
     * Check if fields needs label
562
     *
563
     * @return bool
564
     */
565 31
    protected function needsLabel()
566
    {
567
        // If field is <select> and child of choice, we don't need label for it
568 31
        $isChildSelect = $this->type == 'select' && $this->getOption('is_child') === true;
569
570 31
        if ($this->type == 'hidden' || $isChildSelect) {
571 9
            return false;
572
        }
573
574 27
        return true;
575
    }
576
577
    /**
578
     * Disable field
579
     *
580
     * @return $this
581
     */
582 1
    public function disable()
583
    {
584 1
        $this->setOption('attr.disabled', 'disabled');
585
586 1
        return $this;
587
    }
588
589
    /**
590
     * Enable field
591
     *
592
     * @return $this
593
     */
594 1
    public function enable()
595
    {
596 1
        array_forget($this->options, 'attr.disabled');
597
598 1
        return $this;
599
    }
600
601
    /**
602
     * Get validation rules for a field if any with label for attributes
603
     *
604
     * @return array|null
605
     */
606 7
    public function getValidationRules()
607
    {
608 7
        $rules = $this->getOption('rules', []);
609 7
        $name = $this->getNameKey();
610 7
        $messages = $this->getOption('error_messages', []);
611 7
        $formName = $this->parent->getName();
612
613 7
        if ($messages && $formName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $formName of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
614 1
            $newMessages = [];
615 1
            foreach ($messages as $messageKey => $message) {
616 1
                $messageKey = sprintf('%s.%s', $formName, $messageKey);
617 1
                $newMessages[$messageKey] = $message;
618
            }
619 1
            $messages = $newMessages;
620
        }
621
622 7
        if (!$rules) {
623 1
            return [];
624
        }
625
626
        return [
627 7
            'rules' => [$name => $rules],
628 7
            'attributes' => [$name => $this->getOption('label')],
629 7
            'error_messages' => $messages
630
        ];
631
    }
632
633
    /**
634
     * Get this field's attributes, probably just one.
635
     *
636
     * @return array
637
     */
638 1
    public function getAllAttributes()
639
    {
640 1
        return [$this->getNameKey()];
641
    }
642
643
    /**
644
     * Get value property
645
     *
646
     * @param mixed|null $default
647
     * @return mixed
648
     */
649 34
    public function getValue($default = null)
650
    {
651 34
        return $this->getOption($this->valueProperty, $default);
652
    }
653
654
    /**
655
     * Get default value property
656
     *
657
     * @param mixed|null $default
658
     * @return mixed
659
     */
660 31
    public function getDefaultValue($default = null)
661
    {
662 31
        return $this->getOption($this->defaultValueProperty, $default);
663
    }
664
665
    /**
666
     * Check if provided value is valid for this type
667
     *
668
     * @return bool
669
     */
670 76
    protected function isValidValue($value)
671
    {
672 76
        return $value !== null;
673
    }
674
}
675