Passed
Push — 5.x ( 442566...811cbc )
by Enjoys
02:46
created

AttributeFactory::getClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\Forms;
6
7
use Closure;
8
use Enjoys\Forms\Attributes\Base;
9
use Enjoys\Forms\Interfaces\AttributeInterface;
10
use Webmozart\Assert\Assert;
11
12
final class AttributeFactory
13
{
14
15 334
    public static function create(string $name, mixed $value = null): AttributeInterface
16
    {
17 334
        return self::getClass($name)->add($value);
18
    }
19
20
    /**
21
     * @param array $attributesKeyValue
22
     * @return AttributeInterface[]
23
     */
24 304
    public static function createFromArray(array $attributesKeyValue): array
25
    {
26 304
        $attributes = [];
27
28
        /** @var Closure|scalar|null $value */
29 304
        foreach ($attributesKeyValue as $name => $value) {
30 304
            if (is_int($name) && is_string($value)) {
31 34
                $attributes[] = self::create($value);
32 34
                continue;
33
            }
34 301
            Assert::string($name);
35 301
            $attributes[] = self::create($name, $value);
36
        }
37 303
        return $attributes;
38
    }
39
40
    /**
41
     * @param string $name
42
     * @return AttributeInterface
43
     */
44 334
    private static function getClass(string $name): AttributeInterface
45
    {
46
        /** @var class-string<AttributeInterface> $classString */
47 334
        $classString = sprintf('\Enjoys\Forms\Attributes\%sAttribute', ucfirst(strtolower($name)));
48 334
        if (class_exists($classString)) {
49 326
            $attributeClass = new $classString();
50
        } else {
51 301
            $attributeClass = (new Base())->withName($name);
52
        }
53 334
        return $attributeClass;
54
    }
55
}
56