Completed
Pull Request — master (#406)
by Kristijan
03:36
created

FormHelper::appendMessagesWithPrefix()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 3
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
ccs 7
cts 7
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 mixed $customConfig
108
     * @return mixed
109
     */
110 129
    public function getConfig($key = null, $default = null, $customConfig = null)
111
    {
112 129
        $config = $this->config;
113 129
        if (is_array($customConfig)) {
114
            $config = array_replace_recursive($config, $customConfig);
115
        }
116
117 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...
118 129
            $returnConfig = array_get($config, $key, $default);
119
        }
120
        else {
121
            $returnConfig = $config;
122
        }
123
124 129
        return $returnConfig;
125
    }
126
127
    /**
128
     * @return View
129
     */
130 38
    public function getView()
131
    {
132 38
        return $this->view;
133
    }
134
135
    /**
136
     * Merge options array.
137
     *
138
     * @param array $first
139
     * @param array $second
140
     * @return array
141
     */
142 129
    public function mergeOptions(array $first, array $second)
143
    {
144 129
        return array_replace_recursive($first, $second);
145
    }
146
147
    /**
148
     * Get proper class for field type.
149
     *
150
     * @param $type
151
     * @return string
152
     */
153 86
    public function getFieldType($type)
154
    {
155 86
        $types = array_keys(static::$availableFieldTypes);
156
157 86
        if (!$type || trim($type) == '') {
158 1
            throw new \InvalidArgumentException('Field type must be provided.');
159
        }
160
161 85
        if ($this->hasCustomField($type)) {
162 2
            return $this->customTypes[$type];
163
        }
164
165 83
        if (!in_array($type, $types)) {
166 2
            throw new \InvalidArgumentException(
167 2
                sprintf(
168 2
                    'Unsupported field type [%s]. Available types are: %s',
169 2
                    $type,
170 2
                    join(', ', array_merge($types, array_keys($this->customTypes)))
171
                )
172
            );
173
        }
174
175 81
        $namespace = __NAMESPACE__.'\\Fields\\';
176
177 81
        return $namespace . static::$availableFieldTypes[$type];
178
    }
179
180
    /**
181
     * Convert array of attributes to html attributes.
182
     *
183
     * @param $options
184
     * @return string
185
     */
186 102
    public function prepareAttributes($options)
187
    {
188 102
        if (!$options) {
189 13
            return null;
190
        }
191
192 102
        $attributes = [];
193
194 102
        foreach ($options as $name => $option) {
195 102
            if ($option !== null) {
196 102
                $name = is_numeric($name) ? $option : $name;
197 102
                $attributes[] = $name.'="'.$option.'" ';
198
            }
199
        }
200
201 102
        return join('', $attributes);
202
    }
203
204
    /**
205
     * Add custom field.
206
     *
207
     * @param $name
208
     * @param $class
209
     */
210 3
    public function addCustomField($name, $class)
211
    {
212 3
        if (!$this->hasCustomField($name)) {
213 3
            return $this->customTypes[$name] = $class;
214
        }
215
216 1
        throw new \InvalidArgumentException('Custom field ['.$name.'] already exists on this form object.');
217
    }
218
219
    /**
220
     * Load custom field types from config file.
221
     */
222 129
    private function loadCustomTypes()
223
    {
224 129
        $customFields = (array) $this->getConfig('custom_fields');
225
226 129
        if (!empty($customFields)) {
227 1
            foreach ($customFields as $fieldName => $fieldClass) {
228 1
                $this->addCustomField($fieldName, $fieldClass);
229
            }
230
        }
231 129
    }
232
233
    /**
234
     * Check if custom field with provided name exists
235
     * @param string $name
236
     * @return boolean
237
     */
238 86
    public function hasCustomField($name)
239
    {
240 86
        return array_key_exists($name, $this->customTypes);
241
    }
242
243
    /**
244
     * @param object $model
245
     * @return object|null
246
     */
247 4
    public function convertModelToArray($model)
248
    {
249 4
        if (!$model) {
250 1
            return null;
251
        }
252
253 4
        if ($model instanceof Model) {
254 2
            return $model->toArray();
255
        }
256
257 3
        if ($model instanceof Collection) {
258 2
            return $model->all();
259
        }
260
261 2
        return $model;
262
    }
263
264
    /**
265
     * Format the label to the proper format.
266
     *
267
     * @param $name
268
     * @return string
269
     */
270 100
    public function formatLabel($name)
271
    {
272 100
        if (!$name) {
273 1
            return null;
274
        }
275
276 100
        if ($this->translator->has($name)) {
277 2
            $translatedName = $this->translator->get($name);
278
279 2
            if (is_string($translatedName)) {
280 2
                return $translatedName;
281
            }
282
        }
283
284 98
        return ucfirst(str_replace('_', ' ', $name));
285
    }
286
287
    /**
288
     * @param FormField $field
289
     * @return RulesParser
290
     */
291 101
    public function createRulesParser(FormField $field)
292
    {
293 101
        return new RulesParser($field);
294
    }
295
296
    /**
297
     * @param FormField[] $fields
298
     * @return array
299
     */
300 9
    public function mergeFieldsRules($fields)
301
    {
302 9
        $rules = [];
303 9
        $attributes = [];
304 9
        $messages = [];
305
306 9
        foreach ($fields as $field) {
307 9
            if ($fieldRules = $field->getValidationRules()) {
308 9
                $rules = array_merge($rules, $fieldRules['rules']);
309 9
                $attributes = array_merge($attributes, $fieldRules['attributes']);
310 9
                $messages = array_merge($messages, $fieldRules['error_messages']);
311
            }
312
        }
313
314
        return [
315 9
            'rules' => $rules,
316 9
            'attributes' => $attributes,
317 9
            'error_messages' => $messages
318
        ];
319
    }
320
321
    /**
322
     * @param array $fields
323
     * @return array
324
     */
325 3
    public function mergeAttributes(array $fields)
326
    {
327 3
        $attributes = [];
328 3
        foreach ($fields as $field) {
329 3
            $attributes = array_merge($attributes, $field->getAllAttributes());
330
        }
331
332 3
        return $attributes;
333
    }
334
335
    /**
336
     * Alter a form's values recursively according to its fields.
337
     *
338
     * @param  Form  $form
339
     * @param  array $values
340
     * @return void
341
     */
342 3
    public function alterFieldValues(Form $form, array &$values)
343
    {
344
        // Alter the form itself
345 3
        $form->alterFieldValues($values);
346
347
        // Alter the form's child forms recursively
348 3
        foreach ($form->getFields() as $name => $field) {
349 3
            if (method_exists($field, 'alterFieldValues')) {
350 2
                $fullName = $this->transformToDotSyntax($name);
351
352 2
                $subValues = Arr::get($values, $fullName);
353 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...
354 3
                Arr::set($values, $fullName, $subValues);
355
            }
356
        }
357 3
    }
358
359
    /**
360
     * Alter a form's validity recursively, and add messages with nested form prefix.
361
     *
362
     * @return void
363
     */
364 9
    public function alterValid(Form $form, Form $mainForm, &$isValid)
365
    {
366
        // Alter the form itself
367 9
        $messages = $form->alterValid($mainForm, $isValid);
368
369
        // Add messages to the existing Bag
370 9
        if ($messages) {
371 1
            $messageBag = $mainForm->getValidator()->getMessageBag();
372 1
            $this->appendMessagesWithPrefix($messageBag, $form->getName(), $messages);
373
        }
374
375
        // Alter the form's child forms recursively
376 9
        foreach ($form->getFields() as $name => $field) {
377 9
            if (method_exists($field, 'alterValid')) {
378 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...
379
            }
380
        }
381 9
    }
382
383
    /**
384
     * Add unprefixed messages with prefix to a MessageBag.
385
     *
386
     * @return void
387
     */
388 1
    public function appendMessagesWithPrefix(MessageBag $messageBag, $prefix, array $keyedMessages)
389
    {
390 1
        foreach ($keyedMessages as $key => $messages) {
391 1
            if ($prefix) {
392 1
                $key = $this->transformToDotSyntax($prefix . '[' . $key . ']');
393
            }
394
395 1
            foreach ((array) $messages as $message) {
396 1
                $messageBag->add($key, $message);
397
            }
398
        }
399 1
    }
400
401
    /**
402
     * @param string $string
403
     * @return string
404
     */
405 101
    public function transformToDotSyntax($string)
406
    {
407 101
        return str_replace(['.', '[]', '[', ']'], ['_', '', '.', ''], $string);
408
    }
409
410
    /**
411
     * @param string $string
412
     * @return string
413
     */
414 6
    public function transformToBracketSyntax($string)
415
    {
416 6
        $name = explode('.', $string);
417 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...
418
            return $name[0];
419
        }
420
421 6
        $first = array_shift($name);
422 6
        return $first . '[' . implode('][', $name) . ']';
423
    }
424
425
    /**
426
     * @return TranslatorInterface
427
     */
428 3
    public function getTranslator()
429
    {
430 3
        return $this->translator;
431
    }
432
433
    /**
434
     * Check if field name is valid and not reserved.
435
     *
436
     * @throws \InvalidArgumentException
437
     * @param string $name
438
     * @param string $className
439
     */
440 69
    public function checkFieldName($name, $className)
441
    {
442 69
        if (!$name || trim($name) == '') {
443 2
            throw new \InvalidArgumentException(
444 2
                "Please provide valid field name for class [{$className}]"
445
            );
446
        }
447
448 67
        if (in_array($name, static::$reservedFieldNames)) {
449 2
            throw new \InvalidArgumentException(
450 2
                "Field name [{$name}] in form [{$className}] is a reserved word. Please use a different field name." .
451 2
                "\nList of all reserved words: " . join(', ', static::$reservedFieldNames)
452
            );
453
        }
454
455 65
        return true;
456
    }
457
}
458