-
Notifications
You must be signed in to change notification settings - Fork 0
/
Type.php
62 lines (51 loc) · 1.59 KB
/
Type.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
abstract class Type
{
private static $types = ['boolean', 'integer', 'double', 'string', 'array', 'object'];
private $type = null;
private $value;
final public function __construct($value)
{
$this->makeTypeFromClassName();
$this->checkType();
$this->checkValueType($value);
$this->value = $value;
}
final public static function make($value)
{
return new static($value);
}
final public function __toString()
{
if (is_array($this->value) || is_object($this->value))
return serialize($this->value);
return (string) $this->value;
}
final public function __invoke()
{
return $this->value;
}
final private function makeTypeFromClassName()
{
$className = preg_replace('/(type)+$/', '', $this->buildClassName());
$this->type = $className;
}
final private function buildClassName()
{
$parentClassName = parent::class;
if ($parentClassName && $parentClassName !== self::class)
return strtolower($parentClassName);
return strtolower(static::class);
}
final private function checkType()
{
if (! in_array($this->type, self::$types) || $this->type === null)
throw new InvalidArgumentException("Invalid type given `{$this->type}`.");
}
final private function checkValueType($value)
{
$type = gettype($value);
if ($type !== $this->type)
throw new InvalidArgumentException("Value must be `{$this->type}`, `{$type}` given.");
}
}