1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Papper\ValueConverter; |
4
|
|
|
|
5
|
|
|
use Papper\ValueConverterException; |
6
|
|
|
use Papper\ValueConverterInterface; |
7
|
|
|
|
8
|
|
|
class TypeValueConverter implements ValueConverterInterface |
9
|
|
|
{ |
10
|
|
|
private static $availableTypes = array( |
11
|
|
|
'boolean', |
12
|
|
|
'bool', |
13
|
|
|
'integer', |
14
|
|
|
'int', |
15
|
|
|
'float', |
16
|
|
|
'double', |
17
|
|
|
'string', |
18
|
|
|
'array', |
19
|
|
|
'object', |
20
|
|
|
'null' |
21
|
|
|
); |
22
|
|
|
|
23
|
|
|
private $type; |
24
|
|
|
|
25
|
|
|
public function __construct($type) |
26
|
|
|
{ |
27
|
|
|
if (!in_array($type, self::$availableTypes)) { |
28
|
|
|
$message = sprintf('The type "%s" does not exist. Available types are: %s', $type, implode(', ', self::$availableTypes)); |
29
|
|
|
throw new ValueConverterException($message); |
30
|
|
|
} |
31
|
|
|
$this->type = $type; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function convert($value) |
35
|
|
|
{ |
36
|
|
|
if (!settype($value, $this->type)) { |
37
|
|
|
throw new ValueConverterException('Converting %s to type '); |
38
|
|
|
} |
39
|
|
|
return $value; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public static function boolean() |
43
|
|
|
{ |
44
|
|
|
return new self('boolean'); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public static function integer() |
48
|
|
|
{ |
49
|
|
|
return new self('integer'); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public static function float() |
53
|
|
|
{ |
54
|
|
|
return new self('float'); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public static function string() |
58
|
|
|
{ |
59
|
|
|
return new self('string'); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public static function arr() |
63
|
|
|
{ |
64
|
|
|
return new self('array'); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public static function object() |
68
|
|
|
{ |
69
|
|
|
return new self('object'); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public static function null() |
73
|
|
|
{ |
74
|
|
|
return new self('null'); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|