Option::setDefault()   A
last analyzed

Complexity

Conditions 6
Paths 7

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 16
ccs 10
cts 10
cp 1
rs 9.2222
cc 6
nc 7
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\Forms\Elements;
6
7
use Enjoys\Forms\AttributeFactory;
8
use Enjoys\Forms\Element;
9
use Enjoys\Forms\Interfaces\Fillable;
10
use Enjoys\Forms\Traits\Fill;
11
12
class Option extends Element implements Fillable
13
{
14
    use Fill;
15
16
    protected string $type = 'option';
17
18
19 38
    public function __construct(string $name, ?string $title = null)
20
    {
21 38
        parent::__construct($name, $title);
22 38
        $this->setAttributes(
23 38
            AttributeFactory::createFromArray([
24 38
                'value' => $name,
25 38
            ])
26 38
        );
27 38
        $this->removeAttribute('name');
28 38
        $this->removeAttribute('id');
29
    }
30
31
    /**
32
     *
33
     * @param mixed $value
34
     * @return $this
35
     */
36 36
    protected function setDefault(mixed $value = null): static
37
    {
38 36
        if (is_array($value)) {
39 7
            if (in_array($this->getAttribute('value')?->getValueString(), $value)) {
40 7
                $this->setAttribute(AttributeFactory::create('selected'));
41 7
                return $this;
42
            }
43
        }
44
45 36
        if (is_string($value) || is_numeric($value)) {
46 29
            if ($this->getAttribute('value')?->getValueString() == $value) {
47 6
                $this->setAttribute(AttributeFactory::create('selected'));
48 6
                return $this;
49
            }
50
        }
51 36
        return $this;
52
    }
53
54 10
    public function baseHtml(): string
55
    {
56 10
        if ($this->getLabel() === null) {
57 3
            return sprintf("<option%s>", $this->getAttributesString());
58
        }
59
60 7
        return sprintf("<option%s>%s</option>", $this->getAttributesString(), $this->getLabel() ?? '');
61
    }
62
}
63