Completed
Push — master ( 442463...d4b8b4 )
by Kristijan
18:40 queued 17:26
created

FormHelper::hasCustomField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
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;
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\Events\AfterCollectingFieldRules;
12
use Kris\LaravelFormBuilder\Fields\FormField;
13
use Kris\LaravelFormBuilder\Form;
14
use Kris\LaravelFormBuilder\RulesParser;
15
16
class FormHelper
17
{
18
19
    /**
20
     * @var View
21
     */
22
    protected $view;
23
24
    /**
25
     * @var TranslatorInterface
26
     */
27
    protected $translator;
28
29
    /**
30
     * @var array
31
     */
32
    protected $config;
33
34
    /**
35
     * @var FormBuilder
36
     */
37
    protected $formBuilder;
38
39
    /**
40
     * @var array
41
     */
42
    protected static $reservedFieldNames = [
43
        'save'
44
    ];
45
46
    /**
47
     * All available field types
48
     *
49
     * @var array
50
     */
51
    protected static $availableFieldTypes = [
52
        'text'           => 'InputType',
53
        'email'          => 'InputType',
54
        'url'            => 'InputType',
55
        'tel'            => 'InputType',
56
        'search'         => 'InputType',
57
        'password'       => 'InputType',
58
        'hidden'         => 'InputType',
59
        'number'         => 'InputType',
60
        'date'           => 'InputType',
61
        'file'           => 'InputType',
62
        'image'          => 'InputType',
63
        'color'          => 'InputType',
64
        'datetime-local' => 'InputType',
65
        'month'          => 'InputType',
66
        'range'          => 'InputType',
67
        'time'           => 'InputType',
68
        'week'           => 'InputType',
69
        'select'         => 'SelectType',
70
        'textarea'       => 'TextareaType',
71
        'button'         => 'ButtonType',
72
        'buttongroup'    => 'ButtonGroupType',
73
        'submit'         => 'ButtonType',
74
        'reset'          => 'ButtonType',
75
        'radio'          => 'CheckableType',
76
        'checkbox'       => 'CheckableType',
77
        'choice'         => 'ChoiceType',
78
        'form'           => 'ChildFormType',
79
        'entity'         => 'EntityType',
80
        'collection'     => 'CollectionType',
81
        'repeated'       => 'RepeatedType',
82
        'static'         => 'StaticType'
83
    ];
84
85
    /**
86
     * Custom types
87
     *
88
     * @var array
89
     */
90
    private $customTypes = [];
91
92
    /**
93
     * @param View    $view
94
     * @param Translator $translator
95
     * @param array   $config
96
     */
97 130
    public function __construct(View $view, Translator $translator, array $config = [])
98
    {
99 130
        $this->view = $view;
100 130
        $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...
101 130
        $this->config = $config;
102 130
        $this->loadCustomTypes();
103 130
    }
104
105
    /**
106
     * @param string $key
107
     * @param string $default
108
     * @param array $customConfig
109
     * @return mixed
110
     */
111 130
    public function getConfig($key = null, $default = null, $customConfig = [])
112
    {
113 130
        $config = array_replace_recursive($this->config, $customConfig);
114
115 130
        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...
116 130
            return Arr::get($config, $key, $default);
117
        }
118
119
        return $config;
120
    }
121
122
    /**
123
     * @return View
124
     */
125 38
    public function getView()
126
    {
127 38
        return $this->view;
128
    }
129
130
    /**
131
     * Merge options array.
132
     *
133
     * @param array $first
134
     * @param array $second
135
     * @return array
136
     */
137 130
    public function mergeOptions(array $first, array $second)
138
    {
139 130
        return array_replace_recursive($first, $second);
140
    }
141
142
    /**
143
     * Get proper class for field type.
144
     *
145
     * @param $type
146
     * @return string
147
     */
148 87
    public function getFieldType($type)
149
    {
150 87
        $types = array_keys(static::$availableFieldTypes);
151
152 87
        if (!$type || trim($type) == '') {
153 1
            throw new \InvalidArgumentException('Field type must be provided.');
154
        }
155
156 86
        if ($this->hasCustomField($type)) {
157 2
            return $this->customTypes[$type];
158
        }
159
160 84
        if (!in_array($type, $types)) {
161 2
            throw new \InvalidArgumentException(
162 2
                sprintf(
163 2
                    'Unsupported field type [%s]. Available types are: %s',
164 2
                    $type,
165 2
                    join(', ', array_merge($types, array_keys($this->customTypes)))
166
                )
167
            );
168
        }
169
170 82
        $namespace = __NAMESPACE__.'\\Fields\\';
171
172 82
        return $namespace . static::$availableFieldTypes[$type];
173
    }
174
175
    /**
176
     * Convert array of attributes to html attributes.
177
     *
178
     * @param $options
179
     * @return string
180
     */
181 103
    public function prepareAttributes($options)
182
    {
183 103
        if (!$options) {
184 13
            return null;
185
        }
186
187 103
        $attributes = [];
188
189 103
        foreach ($options as $name => $option) {
190 103
            if ($option !== null) {
191 103
                $name = is_numeric($name) ? $option : $name;
192 103
                $attributes[] = $name.'="'.$option.'" ';
193
            }
194
        }
195
196 103
        return join('', $attributes);
197
    }
198
199
    /**
200
     * Add custom field.
201
     *
202
     * @param $name
203
     * @param $class
204
     */
205 3
    public function addCustomField($name, $class)
206
    {
207 3
        if (!$this->hasCustomField($name)) {
208 3
            return $this->customTypes[$name] = $class;
209
        }
210
211 1
        throw new \InvalidArgumentException('Custom field ['.$name.'] already exists on this form object.');
212
    }
213
214
    /**
215
     * Load custom field types from config file.
216
     */
217 130
    private function loadCustomTypes()
218
    {
219 130
        $customFields = (array) $this->getConfig('custom_fields');
220
221 130
        if (!empty($customFields)) {
222 1
            foreach ($customFields as $fieldName => $fieldClass) {
223 1
                $this->addCustomField($fieldName, $fieldClass);
224
            }
225
        }
226 130
    }
227
228
    /**
229
     * Check if custom field with provided name exists
230
     * @param string $name
231
     * @return boolean
232
     */
233 87
    public function hasCustomField($name)
234
    {
235 87
        return array_key_exists($name, $this->customTypes);
236
    }
237
238
    /**
239
     * @param object $model
240
     * @return object|null
241
     */
242 4
    public function convertModelToArray($model)
243
    {
244 4
        if (!$model) {
245 1
            return null;
246
        }
247
248 4
        if ($model instanceof Model) {
249 2
            return $model->toArray();
250
        }
251
252 3
        if ($model instanceof Collection) {
253 2
            return $model->all();
254
        }
255
256 2
        return $model;
257
    }
258
259
    /**
260
     * Format the label to the proper format.
261
     *
262
     * @param $name
263
     * @return string
264
     */
265 101
    public function formatLabel($name)
266
    {
267 101
        if (!$name) {
268 1
            return null;
269
        }
270
271 101
        if ($this->translator->has($name)) {
272 2
            $translatedName = $this->translator->get($name);
273
274 2
            if (is_string($translatedName)) {
275 2
                return $translatedName;
276
            }
277
        }
278
279 99
        return ucfirst(str_replace('_', ' ', $name));
280
    }
281
282
    /**
283
     * @param FormField $field
284
     * @return RulesParser
285
     */
286 102
    public function createRulesParser(FormField $field)
287
    {
288 102
        return new RulesParser($field);
289
    }
290
291
    /**
292
     * @param FormField $field
293
     * @return array
294
     */
295 9
    public function getFieldValidationRules(FormField $field)
296
    {
297 9
        $fieldRules = $field->getValidationRules();
298
299 9
        if (is_array($fieldRules)) {
300
          $fieldRules = Rules::fromArray($fieldRules)->setFieldName($field->getNameKey());
301
        }
302
303 9
        $formBuilder = $field->getParent()->getFormBuilder();
304 9
        $formBuilder->fireEvent(new AfterCollectingFieldRules($field, $fieldRules));
305
306 9
        return $fieldRules;
307
    }
308
309
    /**
310
     * @param FormField[] $fields
311
     * @return array
312
     */
313 9
    public function mergeFieldsRules($fields)
314
    {
315 9
        $rules = new Rules([]);
316
317 9
        foreach ($fields as $field) {
318 9
            $rules->append($this->getFieldValidationRules($field));
0 ignored issues
show
Documentation introduced by
$this->getFieldValidationRules($field) is of type object<Kris\LaravelFormBuilder\Rules>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
319
        }
320
321 9
        return $rules;
322
    }
323
324
    /**
325
     * @param array $fields
326
     * @return array
327
     */
328 3
    public function mergeAttributes(array $fields)
329
    {
330 3
        $attributes = [];
331 3
        foreach ($fields as $field) {
332 3
            $attributes = array_merge($attributes, $field->getAllAttributes());
333
        }
334
335 3
        return $attributes;
336
    }
337
338
    /**
339
     * Alter a form's values recursively according to its fields.
340
     *
341
     * @param  Form  $form
342
     * @param  array $values
343
     * @return void
344
     */
345 3
    public function alterFieldValues(Form $form, array &$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 = (array) 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 2
                Arr::set($values, $fullName, $subValues);
355
            }
356
        }
357
358
        // Alter the form itself
359 3
        $form->alterFieldValues($values);
360 3
    }
361
362
    /**
363
     * Alter a form's validity recursively, and add messages with nested form prefix.
364
     *
365
     * @return void
366
     */
367 9
    public function alterValid(Form $form, Form $mainForm, &$isValid)
368
    {
369
        // Alter the form itself
370 9
        $messages = $form->alterValid($mainForm, $isValid);
371
372
        // Add messages to the existing Bag
373 9
        if ($messages) {
374 1
            $messageBag = $mainForm->getValidator()->getMessageBag();
375 1
            $this->appendMessagesWithPrefix($messageBag, $form->getName(), $messages);
376
        }
377
378
        // Alter the form's child forms recursively
379 9
        foreach ($form->getFields() as $name => $field) {
380 9
            if (method_exists($field, 'alterValid')) {
381 2
                $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...
382
            }
383
        }
384 9
    }
385
386
    /**
387
     * Add unprefixed messages with prefix to a MessageBag.
388
     *
389
     * @return void
390
     */
391 1
    public function appendMessagesWithPrefix(MessageBag $messageBag, $prefix, array $keyedMessages)
392
    {
393 1
        foreach ($keyedMessages as $key => $messages) {
394 1
            if ($prefix) {
395 1
                $key = $this->transformToDotSyntax($prefix . '[' . $key . ']');
396
            }
397
398 1
            foreach ((array) $messages as $message) {
399 1
                $messageBag->add($key, $message);
400
            }
401
        }
402 1
    }
403
404
    /**
405
     * @param string $string
406
     * @return string
407
     */
408 102
    public function transformToDotSyntax($string)
409
    {
410 102
        return str_replace(['.', '[]', '[', ']'], ['_', '', '.', ''], $string);
411
    }
412
413
    /**
414
     * @param string $string
415
     * @return string
416
     */
417 7
    public function transformToBracketSyntax($string)
418
    {
419 7
        $name = explode('.', $string);
420 7
        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...
421 1
            return $name[0];
422
        }
423
424 6
        $first = array_shift($name);
425 6
        return $first . '[' . implode('][', $name) . ']';
426
    }
427
428
    /**
429
     * @return TranslatorInterface
430
     */
431 3
    public function getTranslator()
432
    {
433 3
        return $this->translator;
434
    }
435
436
    /**
437
     * Check if field name is valid and not reserved.
438
     *
439
     * @throws \InvalidArgumentException
440
     * @param string $name
441
     * @param string $className
442
     */
443 70
    public function checkFieldName($name, $className)
444
    {
445 70
        if (!$name || trim($name) == '') {
446 2
            throw new \InvalidArgumentException(
447 2
                "Please provide valid field name for class [{$className}]"
448
            );
449
        }
450
451 68
        if (in_array($name, static::$reservedFieldNames)) {
452 2
            throw new \InvalidArgumentException(
453 2
                "Field name [{$name}] in form [{$className}] is a reserved word. Please use a different field name." .
454 2
                "\nList of all reserved words: " . join(', ', static::$reservedFieldNames)
455
            );
456
        }
457
458 66
        return true;
459
    }
460
}
461