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

AttributeFactory::getMappedClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

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.9666
cc 1
nc 1
nop 1
crap 1
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 341
    private static function getMappedClass(string $className): Closure
22
    {
23 341
        $mappedClasses = [
24 341
            'class' => function (): AttributeInterface {
25 26
                return new Class_();
26
            },
27 341
            'id' => function (): AttributeInterface {
28 323
                return new Id();
29
            },
30 341
            'action' => function (): AttributeInterface {
31 77
                return new Action();
32
            },
33
        ];
34
35 341
        return $mappedClasses[strtolower($className)] ?? function (string $name): AttributeInterface {
36 308
                return (new Base())->withName($name);
37
        };
38
    }
39
40 341
    public static function create(string $name, mixed $value = null): AttributeInterface
41
    {
42 341
        $closure = self::getMappedClass($name);
43 341
        return $closure($name)->add($value);
44
    }
45
46
    /**
47
     * @param array $attributesKeyValue
48
     * @return AttributeInterface[]
49
     */
50 311
    public static function createFromArray(array $attributesKeyValue): array
51
    {
52 311
        $attributes = [];
53
54
        /** @var Closure|scalar|null $value */
55 311
        foreach ($attributesKeyValue as $name => $value) {
56 311
            if (is_int($name) && is_string($value)) {
57 34
                $attributes[] = self::create($value);
58 34
                continue;
59
            }
60 308
            Assert::string($name);
61 308
            $attributes[] = self::create($name, $value);
62
        }
63 310
        return $attributes;
64
    }
65
}
66