Completed
Push — master ( 9cc7b2...bb332d )
by Kristijan
11s
created

FormHelper::formatLabel()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
ccs 8
cts 8
cp 1
crap 4
1
<?php
2
3
namespace Kris\LaravelFormBuilder;
4
5
use Illuminate\Contracts\Support\MessageBag;
6
use Illuminate\Contracts\View\Factory as View;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Support\Arr;
9
use Illuminate\Support\Collection;
10
use Illuminate\Translation\Translator;
11
use Kris\LaravelFormBuilder\Fields\FormField;
12
use Kris\LaravelFormBuilder\Form;
13
use Kris\LaravelFormBuilder\RulesParser;
14
15
class FormHelper
16
{
17
18
    /**
19
     * @var View
20
     */
21
    protected $view;
22
23
    /**
24
     * @var TranslatorInterface
25
     */
26
    protected $translator;
27
28
    /**
29
     * @var array
30
     */
31
    protected $config;
32
33
    /**
34
     * @var FormBuilder
35
     */
36
    protected $formBuilder;
37
38
    /**
39
     * @var array
40
     */
41
    protected static $reservedFieldNames = [
42
        'save'
43
    ];
44
45
    /**
46
     * All available field types
47
     *
48
     * @var array
49
     */
50
    protected static $availableFieldTypes = [
51
        'text'           => 'InputType',
52
        'email'          => 'InputType',
53
        'url'            => 'InputType',
54
        'tel'            => 'InputType',
55
        'search'         => 'InputType',
56
        'password'       => 'InputType',
57
        'hidden'         => 'InputType',
58
        'number'         => 'InputType',
59
        'date'           => 'InputType',
60
        'file'           => 'InputType',
61
        'image'          => 'InputType',
62
        'color'          => 'InputType',
63
        'datetime-local' => 'InputType',
64
        'month'          => 'InputType',
65
        'range'          => 'InputType',
66
        'time'           => 'InputType',
67
        'week'           => 'InputType',
68
        'select'         => 'SelectType',
69
        'textarea'       => 'TextareaType',
70
        'button'         => 'ButtonType',
71
        'buttongroup'    => 'ButtonGroupType',
72
        'submit'         => 'ButtonType',
73
        'reset'          => 'ButtonType',
74
        'radio'          => 'CheckableType',
75
        'checkbox'       => 'CheckableType',
76
        'choice'         => 'ChoiceType',
77
        'form'           => 'ChildFormType',
78
        'entity'         => 'EntityType',
79
        'collection'     => 'CollectionType',
80
        'repeated'       => 'RepeatedType',
81
        'static'         => 'StaticType'
82
    ];
83
84
    /**
85
     * Custom types
86
     *
87
     * @var array
88
     */
89
    private $customTypes = [];
90
91
    /**
92
     * @param View    $view
93
     * @param Translator $translator
94
     * @param array   $config
95
     */
96 129
    public function __construct(View $view, Translator $translator, array $config = [])
97
    {
98 129
        $this->view = $view;
99 129
        $this->translator = $translator;
0 ignored issues
show
Documentation Bug introduced by
It seems like $translator of type object<Illuminate\Translation\Translator> is incompatible with the declared type object<Kris\LaravelFormB...er\TranslatorInterface> of property $translator.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
100 129
        $this->config = $config;
101 129
        $this->loadCustomTypes();
102 129
    }
103
104
    /**
105
     * @param string $key
106
     * @param string $default
107
     * @param array $customConfig
108
     * @return mixed
109
     */
110 129
    public function getConfig($key = null, $default = null, $customConfig = [])
111
    {
112 129
        $config = array_replace_recursive($this->config, $customConfig);
113
114 129
        if ($key) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $key 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...
115 129
            return array_get($config, $key, $default);
116
        }
117
118
        return $config;
119
    }
120
121
    /**
122
     * @return View
123
     */
124 38
    public function getView()
125
    {
126 38
        return $this->view;
127
    }
128
129
    /**
130
     * Merge options array.
131
     *
132
     * @param array $first
133
     * @param array $second
134
     * @return array
135
     */
136 129
    public function mergeOptions(array $first, array $second)
137
    {
138 129
        return array_replace_recursive($first, $second);
139
    }
140
141
    /**
142
     * Get proper class for field type.
143
     *
144
     * @param $type
145
     * @return string
146
     */
147 86
    public function getFieldType($type)
148
    {
149 86
        $types = array_keys(static::$availableFieldTypes);
150
151 86
        if (!$type || trim($type) == '') {
152 1
            throw new \InvalidArgumentException('Field type must be provided.');
153
        }
154
155 85
        if ($this->hasCustomField($type)) {
156 2
            return $this->customTypes[$type];
157
        }
158
159 83
        if (!in_array($type, $types)) {
160 2
            throw new \InvalidArgumentException(
161 2
                sprintf(
162 2
                    'Unsupported field type [%s]. Available types are: %s',
163 2
                    $type,
164 2
                    join(', ', array_merge($types, array_keys($this->customTypes)))
165
                )
166
            );
167
        }
168
169 81
        $namespace = __NAMESPACE__.'\\Fields\\';
170
171 81
        return $namespace . static::$availableFieldTypes[$type];
172
    }
173
174
    /**
175
     * Convert array of attributes to html attributes.
176
     *
177
     * @param $options
178
     * @return string
179
     */
180 102
    public function prepareAttributes($options)
181
    {
182 102
        if (!$options) {
183 13
            return null;
184
        }
185
186 102
        $attributes = [];
187
188 102
        foreach ($options as $name => $option) {
189 102
            if ($option !== null) {
190 102
                $name = is_numeric($name) ? $option : $name;
191 102
                $attributes[] = $name.'="'.$option.'" ';
192
            }
193
        }
194
195 102
        return join('', $attributes);
196
    }
197
198
    /**
199
     * Add custom field.
200
     *
201
     * @param $name
202
     * @param $class
203
     */
204 3
    public function addCustomField($name, $class)
205
    {
206 3
        if (!$this->hasCustomField($name)) {
207 3
            return $this->customTypes[$name] = $class;
208
        }
209
210 1
        throw new \InvalidArgumentException('Custom field ['.$name.'] already exists on this form object.');
211
    }
212
213
    /**
214
     * Load custom field types from config file.
215
     */
216 129
    private function loadCustomTypes()
217
    {
218 129
        $customFields = (array) $this->getConfig('custom_fields');
219
220 129
        if (!empty($customFields)) {
221 1
            foreach ($customFields as $fieldName => $fieldClass) {
222 1
                $this->addCustomField($fieldName, $fieldClass);
223
            }
224
        }
225 129
    }
226
227
    /**
228
     * Check if custom field with provided name exists
229
     * @param string $name
230
     * @return boolean
231
     */
232 86
    public function hasCustomField($name)
233
    {
234 86
        return array_key_exists($name, $this->customTypes);
235
    }
236
237
    /**
238
     * @param object $model
239
     * @return object|null
240
     */
241 4
    public function convertModelToArray($model)
242
    {
243 4
        if (!$model) {
244 1
            return null;
245
        }
246
247 4
        if ($model instanceof Model) {
248 2
            return $model->toArray();
249
        }
250
251 3
        if ($model instanceof Collection) {
252 2
            return $model->all();
253
        }
254
255 2
        return $model;
256
    }
257
258
    /**
259
     * Format the label to the proper format.
260
     *
261
     * @param $name
262
     * @return string
263
     */
264 100
    public function formatLabel($name)
265
    {
266 100
        if (!$name) {
267 1
            return null;
268
        }
269
270 100
        if ($this->translator->has($name)) {
271 2
            $translatedName = $this->translator->get($name);
272
273 2
            if (is_string($translatedName)) {
274 2
                return $translatedName;
275
            }
276
        }
277
278 98
        return ucfirst(str_replace('_', ' ', $name));
279
    }
280
281
    /**
282
     * @param FormField $field
283
     * @return RulesParser
284
     */
285 101
    public function createRulesParser(FormField $field)
286
    {
287 101
        return new RulesParser($field);
288
    }
289
290
    /**
291
     * @param FormField[] $fields
292
     * @return array
293
     */
294 9
    public function mergeFieldsRules($fields)
295
    {
296 9
        $rules = [];
297 9
        $attributes = [];
298 9
        $messages = [];
299
300 9
        foreach ($fields as $field) {
301 9
            if ($fieldRules = $field->getValidationRules()) {
302 9
                $rules = array_merge($rules, $fieldRules['rules']);
303 9
                $attributes = array_merge($attributes, $fieldRules['attributes']);
304 9
                $messages = array_merge($messages, $fieldRules['error_messages']);
305
            }
306
        }
307
308
        return [
309 9
            'rules' => $rules,
310 9
            'attributes' => $attributes,
311 9
            'error_messages' => $messages
312
        ];
313
    }
314
315
    /**
316
     * @param array $fields
317
     * @return array
318
     */
319 3
    public function mergeAttributes(array $fields)
320
    {
321 3
        $attributes = [];
322 3
        foreach ($fields as $field) {
323 3
            $attributes = array_merge($attributes, $field->getAllAttributes());
324
        }
325
326 3
        return $attributes;
327
    }
328
329
    /**
330
     * Alter a form's values recursively according to its fields.
331
     *
332
     * @param  Form  $form
333
     * @param  array $values
334
     * @return void
335
     */
336 3
    public function alterFieldValues(Form $form, array &$values)
337
    {
338
        // Alter the form itself
339 3
        $form->alterFieldValues($values);
340
341
        // Alter the form's child forms recursively
342 3
        foreach ($form->getFields() as $name => $field) {
343 3
            if (method_exists($field, 'alterFieldValues')) {
344 2
                $fullName = $this->transformToDotSyntax($name);
345
346 2
                $subValues = Arr::get($values, $fullName);
347 2
                $field->alterFieldValues($subValues);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Kris\LaravelFormBuilder\Fields\FormField as the method alterFieldValues() does only exist in the following sub-classes of Kris\LaravelFormBuilder\Fields\FormField: Kris\LaravelFormBuilder\Fields\ChildFormType. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
348 3
                Arr::set($values, $fullName, $subValues);
349
            }
350
        }
351 3
    }
352
353
    /**
354
     * Alter a form's validity recursively, and add messages with nested form prefix.
355
     *
356
     * @return void
357
     */
358 9
    public function alterValid(Form $form, Form $mainForm, &$isValid)
359
    {
360
        // Alter the form itself
361 9
        $messages = $form->alterValid($mainForm, $isValid);
362
363
        // Add messages to the existing Bag
364 9
        if ($messages) {
365 1
            $messageBag = $mainForm->getValidator()->getMessageBag();
366 1
            $this->appendMessagesWithPrefix($messageBag, $form->getName(), $messages);
367
        }
368
369
        // Alter the form's child forms recursively
370 9
        foreach ($form->getFields() as $name => $field) {
371 9
            if (method_exists($field, 'alterValid')) {
372 9
                $field->alterValid($mainForm, $isValid);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Kris\LaravelFormBuilder\Fields\FormField as the method alterValid() does only exist in the following sub-classes of Kris\LaravelFormBuilder\Fields\FormField: Kris\LaravelFormBuilder\Fields\ChildFormType. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
373
            }
374
        }
375 9
    }
376
377
    /**
378
     * Add unprefixed messages with prefix to a MessageBag.
379
     *
380
     * @return void
381
     */
382 1
    public function appendMessagesWithPrefix(MessageBag $messageBag, $prefix, array $keyedMessages)
383
    {
384 1
        foreach ($keyedMessages as $key => $messages) {
385 1
            if ($prefix) {
386 1
                $key = $this->transformToDotSyntax($prefix . '[' . $key . ']');
387
            }
388
389 1
            foreach ((array) $messages as $message) {
390 1
                $messageBag->add($key, $message);
391
            }
392
        }
393 1
    }
394
395
    /**
396
     * @param string $string
397
     * @return string
398
     */
399 101
    public function transformToDotSyntax($string)
400
    {
401 101
        return str_replace(['.', '[]', '[', ']'], ['_', '', '.', ''], $string);
402
    }
403
404
    /**
405
     * @param string $string
406
     * @return string
407
     */
408 6
    public function transformToBracketSyntax($string)
409
    {
410 6
        $name = explode('.', $string);
411 6
        if ($name && count($name) == 1) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $name 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...
412
            return $name[0];
413
        }
414
415 6
        $first = array_shift($name);
416 6
        return $first . '[' . implode('][', $name) . ']';
417
    }
418
419
    /**
420
     * @return TranslatorInterface
421
     */
422 3
    public function getTranslator()
423
    {
424 3
        return $this->translator;
425
    }
426
427
    /**
428
     * Check if field name is valid and not reserved.
429
     *
430
     * @throws \InvalidArgumentException
431
     * @param string $name
432
     * @param string $className
433
     */
434 69
    public function checkFieldName($name, $className)
435
    {
436 69
        if (!$name || trim($name) == '') {
437 2
            throw new \InvalidArgumentException(
438 2
                "Please provide valid field name for class [{$className}]"
439
            );
440
        }
441
442 67
        if (in_array($name, static::$reservedFieldNames)) {
443 2
            throw new \InvalidArgumentException(
444 2
                "Field name [{$name}] in form [{$className}] is a reserved word. Please use a different field name." .
445 2
                "\nList of all reserved words: " . join(', ', static::$reservedFieldNames)
446
            );
447
        }
448
449 65
        return true;
450
    }
451
}
452