1
|
|
|
<?php |
2
|
|
|
namespace Desmond; |
3
|
|
|
use Exception; |
4
|
|
|
use Desmond\data_types\AbstractCollection; |
5
|
|
|
use Desmond\data_types\ObjectType; |
6
|
|
|
use Desmond\data_types\StringType; |
7
|
|
|
use Desmond\data_types\NumberType; |
8
|
|
|
use Desmond\data_types\VectorType; |
9
|
|
|
use Desmond\data_types\HashType; |
10
|
|
|
use Desmond\data_types\NilType; |
11
|
|
|
use Desmond\data_types\TrueType; |
12
|
|
|
use Desmond\data_types\FalseType; |
13
|
|
|
|
14
|
|
|
trait TypeHelper { |
15
|
40 |
|
public static function fromPhpType($value) |
16
|
|
|
{ |
17
|
40 |
|
if (is_null($value)) { |
18
|
3 |
|
return new NilType(); |
19
|
37 |
|
} else if (is_string($value)) { |
20
|
20 |
|
return new StringType($value); |
21
|
24 |
|
} else if (is_int($value) || is_float($value)) { |
22
|
14 |
|
return new NumberType($value); |
23
|
15 |
|
} else if (is_bool($value)) { |
24
|
3 |
|
return $value === true ? new TrueType() : new FalseType(); |
25
|
13 |
|
} else if (is_array($value)) { |
26
|
11 |
|
foreach ($value as $key => $data) { |
27
|
11 |
|
$value[$key] = self::fromPhpType($data); |
28
|
|
|
} |
29
|
|
|
// Is associative? |
30
|
11 |
|
if (count(array_filter(array_keys($value), 'is_string')) > 0) { |
31
|
5 |
|
return new HashType($value); |
32
|
|
|
} else { |
33
|
7 |
|
return new VectorType($value); |
34
|
|
|
} |
35
|
2 |
|
} else if (is_object($value)) { |
36
|
1 |
|
return new ObjectType($value); |
37
|
|
|
} else { |
38
|
1 |
|
throw new Exception('Unknown PHP type.'); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
3 |
|
public static function toPhpType($object) |
43
|
|
|
{ |
44
|
3 |
|
if ($object instanceof AbstractCollection) { |
45
|
1 |
|
$values = []; |
46
|
1 |
|
foreach ($object->value() as $key => $value) { |
47
|
1 |
|
$values[$key] = self::toPhpType($value); |
48
|
|
|
} |
49
|
1 |
|
$newValue = $values; |
50
|
|
|
} else { |
51
|
3 |
|
$newValue = $object->value(); |
52
|
|
|
} |
53
|
3 |
|
return $newValue; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|