GluesAttributes::glueAttributes()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 36
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 2 Features 1
Metric Value
eloc 16
c 7
b 2
f 1
dl 0
loc 36
rs 8.8333
cc 7
nc 4
nop 1
1
<?php
2
3
namespace SoareCostin\BladeFormComponents\Traits;
4
5
trait GluesAttributes
6
{
7
    public function glueAttributes($attributesList = null)
8
    {
9
        if (is_null($attributesList)) {
10
            $attributesList = $this->attributesList();
11
        }
12
13
        // Filter out attributes that are not set against this object or that are boolean and false (eg required)
14
        $attributes = collect($attributesList)->filter(function ($attr) {
15
            return isset($this->{$attr}) && ! (is_bool($this->{$attr}) && $this->{$attr} == false);
16
        });
17
18
        // Map attributes from a simple collection to a key="value" format
19
        $pairs = $attributes->map(function ($attr) {
20
            if (is_array($this->{$attr})) {
21
                return sprintf('%s="%s"', $attr, implode(' ', $this->{$attr}));
22
            }
23
24
            if (is_bool($this->{$attr})) {
25
                return $attr;
26
            }
27
28
            return sprintf('%s="%s"', $attr, $this->{$attr});
29
        });
30
31
        $customAttributes = $this->customAttributes();
32
33
        if (! empty($customAttributes)) {
34
            // Merge custom attributes (v-model)
35
            $pairs = $pairs->merge(
36
                collect($customAttributes)->map(function ($attr, $key) {
37
                    return sprintf('%s="%s"', $key, $attr);
38
                })
39
            );
40
        }
41
42
        return $pairs->implode(' ');
43
    }
44
45
    protected function attributesList()
46
    {
47
        return [];
48
    }
49
50
    protected function customAttributes()
51
    {
52
        return [];
53
    }
54
}
55