Completed
Pull Request — master (#256)
by Rudie
07:35 queued 04:47
created

FormField::getParent()   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 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 78
    public function __construct($name, $type, Form $parent, array $options = [])
93
    {
94 78
        $this->name = $name;
95 78
        $this->type = $type;
96 78
        $this->parent = $parent;
97 78
        $this->formHelper = $this->parent->getFormHelper();
98 78
        $this->setTemplate();
99 78
        $this->setDefaultOptions($options);
100 78
        $this->setupValue();
101 73
    }
102
103 78
    protected function setupValue()
104
    {
105 78
        $value = $this->getOption($this->valueProperty);
106 78
        $isChild = $this->getOption('is_child');
107
108 78
        if ($value instanceof \Closure) {
109
            $this->valueClosure = $value;
110
        }
111
112 78
        if (($value === null || $value instanceof \Closure) && !$isChild) {
113 69
            $this->setValue($this->getModelValueAttribute($this->parent->getModel(), $this->name));
114 73
        } elseif (!$isChild) {
115 12
            $this->hasDefault = true;
116 12
        }
117 73
    }
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 30
        }
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 8
        }
159
160 30
        if ($showError) {
161 29
            $showError = $this->parent->haveErrorsEnabled();
162 29
        }
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
                'showError' => $showError
174 30
            ]
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 71
    protected function getModelValueAttribute($model, $name)
186
    {
187 71
        $transformedName = $this->transformKey($name);
188 71
        if (is_string($model)) {
189
            return $model;
190 71
        } elseif (is_object($model)) {
191 2
            return object_get($model, $transformedName);
192 71
        } elseif (is_array($model)) {
193 70
            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 78
    protected function transformKey($key)
204
    {
205 78
        return $this->formHelper->transformToDotSyntax($key);
206
    }
207
208
    /**
209
     * Prepare options for rendering
210
     *
211
     * @param array $options
212
     * @return array
213
     */
214 78
    protected function prepareOptions(array $options = [])
215
    {
216 78
        $helper = $this->formHelper;
217 78
        $rulesParser = new RulesParser($this);
218 78
        $rules = $this->getOption('rules');
219 78
        $parsedRules = $rules ? $rulesParser->parse($rules) : [];
220
221 78
        $this->options = $helper->mergeOptions($this->options, $options);
222
223 78
        foreach (['attr', 'label_attr', 'wrapper'] as $appendable) {
224
            // Append values to the 'class' attribute
225 78
            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 3
                $this->setOption("{$appendable}.class_append", null);
233 3
            }
234 78
        }
235
236 78
        if ($this->getOption('attr.multiple') && !$this->getOption('tmp.multipleBracesSet')) {
237 2
            $this->name = $this->name.'[]';
238 2
            $this->setOption('tmp.multipleBracesSet', true);
239 2
        }
240
241 78
        if ($this->parent->haveErrorsEnabled()) {
242 78
            $this->addErrorClass();
243 78
        }
244
245 78
        if ($this->parent->clientValidationEnabled()) {
246 78
            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 3
                }
254 3
            }
255
256 78
            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 1
            }
260 78
        }
261
262 78
        $this->setOption('wrapperAttrs', $helper->prepareAttributes($this->getOption('wrapper')));
263 78
        $this->setOption('errorAttrs', $helper->prepareAttributes($this->getOption('errors')));
264
265 78
        if ($this->getOption('is_child')) {
266 16
            $this->setOption('labelAttrs', $helper->prepareAttributes($this->getOption('label_attr')));
267 16
        }
268
269 78
        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 1
            );
274 1
        }
275
276 78
        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 45
    public function getNameKey()
308
    {
309 45
        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 78
    public function getOption($option, $default = null)
331
    {
332 78
        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 78
    public function setOption($name, $value)
356
    {
357 78
        array_set($this->options, $name, $value);
358
359 78
        return $this;
360
    }
361
362
    /**
363
     * Get the type of the field
364
     *
365
     * @return string
366
     */
367 45
    public function getType()
368
    {
369 45
        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 1
        }
383
384 1
        return $this;
385
    }
386
387
    /**
388
     * @return Form
389
     */
390 78
    public function getParent()
391
    {
392 78
        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 58
    protected function getDefaults()
411
    {
412 58
        return [];
413
    }
414
415
    /**
416
     * Defaults used across all fields
417
     *
418
     * @return array
419
     */
420 78
    private function allDefaults()
421
    {
422
        return [
423 78
            'wrapper' => ['class' => $this->formHelper->getConfig('defaults.wrapper_class')],
424 78
            'attr' => ['class' => $this->formHelper->getConfig('defaults.field_class')],
425 78
            'help_block' => ['text' => null, 'tag' => 'p', 'attr' => [
426 78
                'class' => $this->formHelper->getConfig('defaults.help_block_class')
427 78
            ]],
428 78
            'value' => null,
429 78
            'default_value' => null,
430 78
            'label' => null,
431 78
            'label_show' => true,
432 78
            'is_child' => false,
433 78
            'label_attr' => ['class' => $this->formHelper->getConfig('defaults.label_class')],
434 78
            'errors' => ['class' => $this->formHelper->getConfig('defaults.error_class')],
435 78
            'rules' => [],
436 78
            'error_messages' => []
437 78
        ];
438
    }
439
440
    /**
441
     * Get real name of the field without form namespace
442
     *
443
     * @return string
444
     */
445 77
    public function getRealName()
446
    {
447 77
        return $this->getOption('real_name', $this->name);
448
    }
449
450
    /**
451
     * @param $value
452
     * @return $this
453
     */
454 72
    public function setValue($value)
455
    {
456 72
        if ($this->hasDefault) {
457 1
            return $this;
458
        }
459
460 72
        $closure = $this->valueClosure;
461
462 72
        if ($closure instanceof \Closure) {
463
            $value = $closure($value ?: null);
464
        }
465
466 72
        if (!$this->isValidValue($value)) {
467 70
            $value = $this->getOption($this->defaultValueProperty);
468 70
        }
469
470 72
        $this->options[$this->valueProperty] = $value;
471
472 72
        return $this;
473
    }
474
475
    /**
476
     * Set the template property on the object
477
     */
478 78
    private function setTemplate()
479
    {
480 78
        $this->template = $this->formHelper->getConfig($this->getTemplate(), $this->getTemplate());
481 78
    }
482
483
    /**
484
     * Add error class to wrapper if validation errors exist
485
     */
486 78
    protected function addErrorClass()
487
    {
488 78
        $errors = $this->parent->getRequest()->session()->get('errors');
489
490 78
        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 78
    }
500
501
502
    /**
503
     * Merge all defaults with field specific defaults and set template if passed
504
     *
505
     * @param array $options
506
     */
507 78
    protected function setDefaultOptions(array $options = [])
508
    {
509 78
        $this->options = $this->formHelper->mergeOptions($this->allDefaults(), $this->getDefaults());
510 78
        $this->options = $this->prepareOptions($options);
511 78
        $this->setupLabel();
512 78
    }
513
514 78
    protected function setupLabel()
515
    {
516 78
        if ($this->getOption('label') !== null) {
517 18
            return;
518
        }
519
520 76
        if ($langName = $this->parent->getLanguageName()) {
521 4
            $label = sprintf('%s.%s', $langName, $this->getRealName());
522 4
        } else {
523 73
            $label = $this->getRealName();
524
        }
525
526 76
        $this->setOption('label', $this->formHelper->formatLabel($label));
527 76
    }
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 7
    public function getValidationRules()
576
    {
577 7
        $rules = $this->getOption('rules', []);
578 7
        $name = $this->getNameKey();
579 7
        $messages = $this->getOption('error_messages', []);
580 7
        $formName = $this->parent->getName();
581
582 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...
583 1
            $newMessages = [];
584 1
            foreach ($messages as $messageKey => $message) {
585 1
                $messageKey = sprintf('%s.%s', $formName, $messageKey);
586 1
                $newMessages[$messageKey] = $message;
587 1
            }
588 1
            $messages = $newMessages;
589 1
        }
590
591 7
        if (!$rules) {
592 1
            return [];
593
        }
594
595
        return [
596 7
            'rules' => [$name => $rules],
597 7
            'attributes' => [$name => $this->getOption('label')],
598
            'error_messages' => $messages
599 7
        ];
600
    }
601
602
    /**
603
     * Get value property
604
     *
605
     * @param mixed|null $default
606
     * @return mixed
607
     */
608 33
    public function getValue($default = null)
609
    {
610 33
        return $this->getOption($this->valueProperty, $default);
611
    }
612
613
    /**
614
     * Get default value property
615
     *
616
     * @param mixed|null $default
617
     * @return mixed
618
     */
619 30
    public function getDefaultValue($default = null)
620
    {
621 30
        return $this->getOption($this->defaultValueProperty, $default);
622
    }
623
624
    /**
625
     * Check if provided value is valid for this type
626
     *
627
     * @return bool
628
     */
629 73
    protected function isValidValue($value)
630
    {
631 73
        return $value !== null;
632
    }
633
}
634