Passed
Push — master ( 34f20f...a12a6d )
by Enjoys
57s queued 12s
created

AttributeFactory   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
eloc 16
c 2
b 0
f 0
dl 0
loc 50
ccs 18
cts 18
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 3 1
A createFromArray() 0 14 4
A getClass() 0 13 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
    /**
15
     * @param string $name
16
     * @param Closure|scalar|null $value
17
     * @return AttributeInterface
18
     * @noinspection PhpMissingParamTypeInspection
19
     */
20 354
    public static function create(string $name, $value = null): AttributeInterface
21
    {
22 354
        return self::getClass($name)->add($value);
23
    }
24
25
    /**
26
     * @param array $attributesKeyValue
27
     * @return AttributeInterface[]
28
     */
29 324
    public static function createFromArray(array $attributesKeyValue): array
30
    {
31 324
        $attributes = [];
32
33
        /** @var Closure|scalar|null $value */
34 324
        foreach ($attributesKeyValue as $name => $value) {
35 324
            if (is_int($name) && is_string($value)) {
36 34
                $attributes[] = self::create($value);
37 34
                continue;
38
            }
39 321
            Assert::string($name);
40 321
            $attributes[] = self::create($name, $value);
41
        }
42 323
        return $attributes;
43
    }
44
45
    /**
46
     * @param string $name
47
     * @return AttributeInterface
48
     */
49 355
    private static function getClass(string $name): AttributeInterface
50
    {
51 355
        $normalizeName = ucfirst(strtolower($name));
52
53
        /** @var class-string<AttributeInterface> $classString */
54 355
        $classString = sprintf('\Enjoys\Forms\Attributes\%sAttribute', $normalizeName);
55 355
        $classFile = sprintf(__DIR__ . '/Attributes/%sAttribute.php', $normalizeName);
56
57 355
        if (is_file($classFile) && class_exists($classString)) {
58 346
            return new $classString();
59
        }
60
61 322
        return (new Base())->withName($name);
62
    }
63
}
64