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
|
|
|
|