Passed
Push — master ( d855a0...34f20f )
by Enjoys
01:02 queued 12s
created

AttributeFactory::getClass()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 10
cc 3
nc 2
nop 1
crap 3
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 339
    public static function create(string $name, mixed $value = null): AttributeInterface
15
    {
16 339
        return self::getClass($name)->add($value);
17
    }
18
19
    /**
20
     * @param array $attributesKeyValue
21
     * @return AttributeInterface[]
22
     */
23 309
    public static function createFromArray(array $attributesKeyValue): array
24
    {
25 309
        $attributes = [];
26
27
        /** @var Closure|scalar|null $value */
28 309
        foreach ($attributesKeyValue as $name => $value) {
29 309
            if (is_int($name) && is_string($value)) {
30 34
                $attributes[] = self::create($value);
31 34
                continue;
32
            }
33 306
            Assert::string($name);
34 306
            $attributes[] = self::create($name, $value);
35
        }
36 308
        return $attributes;
37
    }
38
39
    /**
40
     * @param string $name
41
     * @return AttributeInterface
42
     */
43 340
    private static function getClass(string $name): AttributeInterface
44
    {
45 340
        $normalizeName = ucfirst(strtolower($name));
46
47
        /** @var class-string<AttributeInterface> $classString */
48 340
        $classString = sprintf('\Enjoys\Forms\Attributes\%sAttribute', $normalizeName);
49 340
        $classFile = sprintf(__DIR__ . '/Attributes/%sAttribute.php', $normalizeName);
50
51 340
        if (is_file($classFile) && class_exists($classString)) {
52 331
            return new $classString();
53
        }
54
55 307
        return (new Base())->withName($name);
56
    }
57
}
58