Passed
Pull Request — master (#10)
by Enjoys
05:36
created

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

66
            $class = '\Enjoys\Forms\Elements\\' . \ucfirst($this->/** @scrutinizer ignore-call */ getType());
Loading history...
67
68
69 61
            $element = new $class($fillHandler->getValue(), $fillHandler->getLabel());
70
71 61
            $element->setAttrs(AttributeFactory::createFromArray($fillHandler->getAttributes()), 'fill');
72
73
            /**
74
             * @todo слишком много вложенности if. подумать как переделать
75
             */
76
            /** @var AttributeCollection $fillCollection */
77 61
            $fillCollection = $element->getAttributeCollection('fill');
78 61
            foreach ($fillCollection as $attr) {
79
              //  if (in_array($attr->getName(), ['id', 'name', 'disabled', 'readonly'])) {
80 28
                    $element->setAttr($attr);
81
                 //   $fillCollection->remove($attr);
82
               // }
83
            }
84
85
86
87
88 61
            $this->addElement($element);
89
        }
90 61
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type Enjoys\Forms\Traits\Fill which is incompatible with the type-hinted return Enjoys\Forms\Interfaces\Fillable.
Loading history...
91
    }
92
93
    /**
94
     *
95
     * @return Element[]
96
     */
97 68
    public function getElements(): array
98
    {
99 68
        return $this->elements;
100
    }
101
102
    /**
103
     * @return mixed
104
     */
105 6
    public function getDefaultValue()
106
    {
107 6
        return $this->defaultValue;
108
    }
109
110
111 9
    public function setDefaultValue(mixed $defaultValue): void
112
    {
113 9
        $this->defaultValue = $defaultValue;
114
    }
115
116
117
    /**
118
     * @param Fillable&Element $element
119
     * @return Fillable
120
     */
121 65
    public function addElement(Fillable $element): Fillable
122
    {
123 65
        $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

123
        $element->setParentName($this->/** @scrutinizer ignore-call */ getName());
Loading history...
124 65
        $element->setDefault($this->defaultValue);
0 ignored issues
show
Bug introduced by
The method setDefault() does not exist on Enjoys\Forms\Interfaces\Fillable. Since it exists in all sub-types, consider adding an abstract or default implementation to Enjoys\Forms\Interfaces\Fillable. ( Ignorable by Annotation )

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

124
        $element->/** @scrutinizer ignore-call */ 
125
                  setDefault($this->defaultValue);
Loading history...
125 65
        $this->elements[] = $element;
126 65
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type Enjoys\Forms\Traits\Fill which is incompatible with the type-hinted return Enjoys\Forms\Interfaces\Fillable.
Loading history...
127
    }
128
129
    /**
130
 * @param  array<Fillable&Element> $elements
131
     * @return Fillable
132
     */
133 3
    public function addElements(array $elements): Fillable
134
    {
135 3
        foreach ($elements as $element) {
136 3
            $this->addElement($element);
137
        }
138 3
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this returns the type Enjoys\Forms\Traits\Fill which is incompatible with the type-hinted return Enjoys\Forms\Interfaces\Fillable.
Loading history...
139
    }
140
}
141