Completed
Pull Request — master (#249)
by Rudie
05:22
created

FormField   C

Complexity

Total Complexity 75

Size/Duplication

Total Lines 608
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 95.31%

Importance

Changes 38
Bugs 17 Features 15
Metric Value
c 38
b 17
f 15
dl 0
loc 608
ccs 183
cts 192
cp 0.9531
rs 5.4689
wmc 75
lcom 1
cbo 6

34 Methods

Rating   Name   Duplication   Size   Complexity  
getTemplate() 0 1 ?
A getViewTemplate() 0 4 1
A __construct() 0 10 1
B setupValue() 0 15 6
A getValue() 0 4 1
A getDefaultValue() 0 4 1
A isValidValue() 0 4 1
B render() 0 39 6
A getModelValueAttribute() 0 11 4
A transformKey() 0 4 1
D prepareOptions() 0 51 12
A getName() 0 4 1
A setName() 0 6 1
A getNameKey() 0 4 1
A getOptions() 0 4 1
A getOption() 0 4 1
A setOptions() 0 6 1
A setOption() 0 6 1
A getType() 0 4 1
A setType() 0 8 2
A getParent() 0 4 1
A isRendered() 0 4 1
A getDefaults() 0 4 1
A allDefaults() 0 19 1
A getRealName() 0 4 1
B setValue() 0 20 5
A setTemplate() 0 4 1
B addErrorClass() 0 14 5
A setDefaultOptions() 0 6 1
A setupLabel() 0 14 3
A needsLabel() 0 11 4
A disable() 0 6 1
A enable() 0 6 1
B getValidationRules() 0 26 5

How to fix   Complexity   

Complex Class

Complex classes like FormField often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FormField, and based on these observations, apply Extract Interface, too.

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