Test Failed
Push — master ( ecdde5...dd7a53 )
by Enjoys
06:21
created

Fill::getElements()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 1
c 2
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\Forms\Traits;
6
7
use Enjoys\Forms\FillHandler;
8
9
/**
10
 * Trait Fill
11
 * @package Enjoys\Forms\Traits
12
 */
13
trait Fill
14
{
15
16
    private array $elements = [];
17
    private string $parentName = '';
18
    /**
19
     * @var mixed
20
     */
21
    private $defaultValue = '';
22
23 57
    public function setParentName(string $parentName): void
24
    {
25 57
        $this->parentName = $parentName;
26
//        $this->parent = false;
27 57
    }
28
29 4
    public function getParentName(): string
30
    {
31 4
        return $this->parentName;
32
    }
33
34
//    public function isParent(): bool
35
//    {
36
//        return $this->parent;
37
//    }
38
39
    /**
40
     * @param array|\Closure $data
41
     * @param bool $useTitleAsValue
42
     * @return $this
43
     * @since 3.4.1 Можно использовать замыкания для заполнения. Анонимная функция должна возвращать массив.
44
     * @since 3.4.0 Возвращен порядок установки value из индексированных массивов, т.к. неудобно,
45
     * по умолчанию теперь не надо добавлять пробел в ключи массива, чтобы value был числом
46
     * но добавлен флаг $useTitleAsValue, если он установлен в true, то все будет работать как в версии 2.4.0
47
     * @since 2.4.0 Изменен принцип установки value и id из индексированных массивов
48
     * т.е. [1,2] значения будут 1 и 2 соответственно, а не 0 и 1 как раньше.
49
     * Чтобы использовать число в качестве value отличное от title, необходимо
50
     * в массиве конкретно указать значение key. Например ["40 " => test] (обратите внимание на пробел).
51
     * Из-за того что php преобразует строки, содержащие целое число к int, приходится добавлять
52
     * пробел либо в начало, либо в конец ключа. В итоге пробелы в начале и в конце удаляются автоматически.
53
     */
54 53
    public function fill($data, $useTitleAsValue = false): self
55
    {
56 53
        if ($data instanceof \Closure) {
57 2
            $data = $data();
58
        }
59
60 53
        if (!is_array($data)) {
61 1
            throw new \InvalidArgumentException('Fill data must be array or closure returned array');
62
        }
63
64 52
        foreach ($data as $value => $title) {
65 52
            $fillHandler = new FillHandler($value, $title, $useTitleAsValue);
66
67 52
            $class = '\Enjoys\Forms\Elements\\' . \ucfirst($this->getType());
0 ignored issues
show
Bug introduced by
It seems like getType() 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

67
            $class = '\Enjoys\Forms\Elements\\' . \ucfirst($this->/** @scrutinizer ignore-call */ getType());
Loading history...
68
69
70 52
            $element = new $class($fillHandler->getValue(), $fillHandler->getLabel());
71 52
            $element->setParentName($this->getName());
0 ignored issues
show
Bug introduced by
It seems like getName() 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

71
            $element->setParentName($this->/** @scrutinizer ignore-call */ getName());
Loading history...
72 52
            $element->setAttributes($fillHandler->getAttributes(), 'fill');
73
74
            /**
75
             * @todo слишком много вложенности if. подумать как переделать
76
             */
77 52
            foreach ($element->getAttributes('fill') as $k => $v) {
78 22
                if (in_array($k, ['id', 'name', 'disabled', 'readonly'])) {
79 22
                    if ($element->getAttribute($k, 'fill') !== false) {
80 22
                        $element->setAttribute($k, $element->getAttribute($k, 'fill'));
81 22
                        $element->removeAttribute($k, 'fill');
82
                    }
83
                }
84
            }
85
86
87 52
            $element->setDefault($this->defaultValue);
88
89 52
            $this->elements[] = $element;
90
        }
91 52
        return $this;
92
    }
93
94
    /**
95
     *
96
     * @return array
97
     */
98 55
    public function getElements(): array
99
    {
100 55
        return $this->elements;
101
    }
102
103
    /**
104
     * @return mixed
105
     */
106 1
    public function getDefaultValue()
107
    {
108 1
        return $this->defaultValue;
109
    }
110
111
112
}
113