Completed
Pull Request — master (#248)
by Rudie
13:15
created

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