|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Mvkasatkin\typecast\type; |
|
4
|
|
|
|
|
5
|
|
|
use Mvkasatkin\typecast\Cast; |
|
6
|
|
|
use Mvkasatkin\typecast\Exception; |
|
7
|
|
|
|
|
8
|
|
|
class Factory |
|
9
|
|
|
{ |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @param string|TypeClosure|\Closure $type |
|
13
|
|
|
* |
|
14
|
|
|
* @return CastInterface |
|
15
|
|
|
* @throws \Mvkasatkin\typecast\Exception |
|
16
|
|
|
*/ |
|
17
|
|
|
public function createType($type): CastInterface |
|
18
|
|
|
{ |
|
19
|
|
|
$result = null; |
|
20
|
|
|
if ($type instanceof \Closure) { |
|
21
|
|
|
$result = new TypeClosure($type); |
|
22
|
|
|
} elseif (\in_array($type, Cast::TYPES, true)) { |
|
23
|
|
|
switch ($type) { |
|
24
|
|
|
case Cast::INT: |
|
25
|
|
|
$result = new TypeInt(); |
|
26
|
|
|
break; |
|
27
|
|
|
case Cast::BOOL: |
|
28
|
|
|
$result = new TypeBool(); |
|
29
|
|
|
break; |
|
30
|
|
|
case Cast::FLOAT: |
|
31
|
|
|
$result = new TypeFloat(); |
|
32
|
|
|
break; |
|
33
|
|
|
case Cast::STRING: |
|
34
|
|
|
$result = new TypeString(); |
|
35
|
|
|
break; |
|
36
|
|
|
case Cast::BINARY: |
|
37
|
|
|
$result = new TypeBinary(); |
|
38
|
|
|
break; |
|
39
|
|
|
case Cast::OBJECT: |
|
40
|
|
|
$result = new TypeObject(); |
|
41
|
|
|
break; |
|
42
|
|
|
case Cast::UNSET: |
|
43
|
|
|
$result = new TypeUnset(); |
|
44
|
|
|
break; |
|
45
|
|
|
case Cast::ARRAY: |
|
46
|
|
|
$result = new TypeArray(); |
|
47
|
|
|
break; |
|
48
|
|
|
} |
|
49
|
|
|
} elseif ($type instanceof CastInterface) { |
|
50
|
|
|
$result = $type; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
if ($result === null) { |
|
54
|
|
|
throw new Exception('Type not found'); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return $result; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* @param $type |
|
62
|
|
|
* |
|
63
|
|
|
* @return TypeArrayOfType |
|
64
|
|
|
* @throws \Mvkasatkin\typecast\Exception |
|
65
|
|
|
*/ |
|
66
|
|
|
public function createArrayOfType($type): TypeArrayOfType |
|
67
|
|
|
{ |
|
68
|
|
|
return new TypeArrayOfType($type); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @param array $config |
|
73
|
|
|
* |
|
74
|
|
|
* @return TypeArrayOfType|null |
|
75
|
|
|
* @throws \Mvkasatkin\typecast\Exception |
|
76
|
|
|
*/ |
|
77
|
|
|
public function checkArrayOfType(array $config) |
|
78
|
|
|
{ |
|
79
|
|
|
if (\count($config) === 1 && isset($config[0])) { |
|
80
|
|
|
$type = $this->createType($config[0]); |
|
81
|
|
|
return $this->createArrayOfType($type); |
|
82
|
|
|
} |
|
83
|
|
|
return null; |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|