HasAttribsTrait   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Test Coverage

Coverage 96%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 55
ccs 24
cts 25
cp 0.96
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getAllowedAttributes() 0 3 1
A renderAttributes() 0 24 4
A canRenderAttribute() 0 10 4
1
<?php
2
3
namespace Nip\Form\Renderer\Traits;
4
5
use Nip\Utility\Str;
6
7
/**
8
 * Trait HasAttribsTrait
9
 * @package Nip\Form\Renderer\Traits
10
 */
11
trait HasAttribsTrait
12
{
13
    /**
14
     * @param array $overrides
15
     * @return string
16
     */
17 1
    public function renderAttributes($overrides = [])
18
    {
19 1
        $attribs = $this->getElement()->getAttribs();
0 ignored issues
show
Bug introduced by
It seems like getElement() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

19
        $attribs = $this->/** @scrutinizer ignore-call */ getElement()->getAttribs();
Loading history...
20 1
        if (!isset($attribs['title'])) {
21 1
            $attribs['title'] = $this->getElement()->getLabel();
22
        }
23 1
        $allowedAttribs = $this->getAllowedAttributes();
24 1
        $attribs = array_filter(
25 1
            $attribs,
26
            function ($key) use ($allowedAttribs) {
27 1
                return $this->canRenderAttribute($key, $allowedAttribs);
28 1
            },
29 1
            ARRAY_FILTER_USE_KEY
30
        );
31 1
        $return = '';
32 1
        foreach ($attribs as $name => $value) {
33 1
            if (in_array($name, array_keys($overrides))) {
34
                $value = $overrides[$name];
35
            }
36
37 1
            $return .= ' ' . $name . '="' . $value . '"';
38
        }
39
40 1
        return $return;
41
    }
42
43
    /**
44
     * @return array
45
     */
46 1
    public function getAllowedAttributes()
47
    {
48 1
        return ['id', 'name', 'style', 'class', 'title', 'read_only', 'disabled'];
49
    }
50
51
    /**
52
     * @param $name
53
     * @param null $allowed
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $allowed is correct as it would always require null to be passed?
Loading history...
54
     * @return bool
55
     */
56 1
    protected function canRenderAttribute($name, $allowed = null)
57
    {
58 1
        $allowed = $allowed ?: $this->getAllowedAttributes();
0 ignored issues
show
introduced by
$allowed is of type null, thus it always evaluated to false.
Loading history...
59 1
        if (in_array($name, $allowed)) {
60 1
            return true;
61
        }
62 1
        if (Str::startsWith($name, 'data-')) {
63 1
            return true;
64
        }
65 1
        return false;
66
    }
67
}
68