Passed
Push — 5.x ( 65a76f...3a1e20 )
by Enjoys
59s queued 13s
created

AttributeFactory::createFromArray()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 14
ccs 9
cts 9
cp 1
rs 10
cc 4
nc 3
nop 1
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\Forms;
6
7
use Closure;
8
use Enjoys\Forms\Attributes\Action;
9
use Enjoys\Forms\Attributes\Base;
10
use Enjoys\Forms\Attributes\Class_;
11
use Enjoys\Forms\Attributes\Id;
12
use Enjoys\Forms\Interfaces\AttributeInterface;
13
use Webmozart\Assert\Assert;
14
15
final class AttributeFactory
16
{
17
    /**
18
     * @param string $className
19
     * @return Closure(string):AttributeInterface
20
     */
21 339
    private static function getMappedClass(string $className): Closure
22
    {
23 339
        $mappedClasses = [
24 339
            'class' => function (): AttributeInterface {
25 26
                return new Class_();
26
            },
27 339
            'id' => function (): AttributeInterface {
28 321
                return new Id();
29
            },
30 339
            'action' => function (): AttributeInterface {
31 77
                return new Action();
32
            },
33
        ];
34
35 339
        return $mappedClasses[strtolower($className)] ?? function (string $name): AttributeInterface {
36 306
                return (new Base())->withName($name);
37
        };
38
    }
39
40 339
    public static function create(string $name, mixed $value = null): AttributeInterface
41
    {
42 339
        $closure = self::getMappedClass($name);
43 339
        return $closure($name)->add($value);
44
    }
45
46
    /**
47
     * @param array $attributesKeyValue
48
     * @return AttributeInterface[]
49
     */
50 309
    public static function createFromArray(array $attributesKeyValue): array
51
    {
52 309
        $attributes = [];
53
54
        /** @var Closure|scalar|null $value */
55 309
        foreach ($attributesKeyValue as $name => $value) {
56 309
            if (is_int($name) && is_string($value)) {
57 34
                $attributes[] = self::create($value);
58 34
                continue;
59
            }
60 306
            Assert::string($name);
61 306
            $attributes[] = self::create($name, $value);
62
        }
63 308
        return $attributes;
64
    }
65
}
66