1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of Railt package. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
declare(strict_types=1); |
9
|
|
|
|
10
|
|
|
namespace Railt\Reflection; |
11
|
|
|
|
12
|
|
|
use Railt\Reflection\Common\Renderer; |
13
|
|
|
use Railt\Reflection\Common\Serializable; |
14
|
|
|
use Railt\Reflection\Contracts\Type as TypeInterface; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Class BaseType |
18
|
|
|
*/ |
19
|
|
|
abstract class Type implements TypeInterface |
20
|
|
|
{ |
21
|
|
|
use Serializable; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var Type[] |
25
|
|
|
*/ |
26
|
|
|
private static $instances = []; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var array |
30
|
|
|
*/ |
31
|
|
|
private static $types = []; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @var string |
35
|
|
|
*/ |
36
|
|
|
protected $name; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* BaseType constructor. |
40
|
|
|
* @param string $name |
41
|
|
|
*/ |
42
|
|
|
public function __construct(string $name) |
43
|
|
|
{ |
44
|
|
|
$this->name = $name; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param string $type |
49
|
|
|
* @return Type |
50
|
|
|
*/ |
51
|
|
|
public static function of(string $type): Type |
52
|
|
|
{ |
53
|
|
|
return self::$instances[$type] ?? ( |
54
|
|
|
self::$instances[$type] = new static($type) |
55
|
|
|
); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @return string |
60
|
|
|
*/ |
61
|
|
|
public function getName(): string |
62
|
|
|
{ |
63
|
|
|
return $this->name; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param TypeInterface $type |
68
|
|
|
* @return bool |
69
|
|
|
*/ |
70
|
|
|
public function instanceOf(TypeInterface $type): bool |
71
|
|
|
{ |
72
|
|
|
return $this instanceof $type; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @return string |
77
|
|
|
*/ |
78
|
|
|
public function __toString(): string |
79
|
|
|
{ |
80
|
|
|
return Renderer::typeName($this->getName()); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @param string $name |
85
|
|
|
* @return bool |
86
|
|
|
* @throws \ReflectionException |
87
|
|
|
*/ |
88
|
|
|
public static function isValid(string $name): bool |
89
|
|
|
{ |
90
|
|
|
if (self::$types === []) { |
91
|
|
|
$reflection = new \ReflectionClass(static::class); |
92
|
|
|
|
93
|
|
|
foreach ($reflection->getConstants() as $constant) { |
94
|
|
|
self::$types[] = $constant; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
return \in_array($name, self::$types, true); |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|