10
10
*/
11
11
class IntegerEncoder implements Encoder
12
12
{
13
+ /** @var array Default values for options in the encoder */
14
+ private static $ defaultOptions = [
15
+ 'integer.type ' => 'decimal ' ,
16
+ ];
17
+
13
18
public function getDefaultOptions ()
14
19
{
15
- return [] ;
20
+ return self :: $ defaultOptions ;
16
21
}
17
22
18
23
public function supports ($ value )
@@ -22,12 +27,60 @@ public function supports($value)
22
27
23
28
public function encode ($ value , $ depth , array $ options , callable $ encode )
24
29
{
25
- $ string = (string ) $ value ;
30
+ $ encoders = [
31
+ 'binary ' => function ($ value ) {
32
+ return $ this ->encodeBinary ($ value );
33
+ },
34
+ 'octal ' => function ($ value ) {
35
+ return $ this ->encodeOctal ($ value );
36
+ },
37
+ 'decimal ' => function ($ value , $ options ) {
38
+ return $ this ->encodeDecimal ($ value , $ options );
39
+ },
40
+ 'hexadecimal ' => function ($ value ) {
41
+ return $ this ->encodeHexadecimal ($ value );
42
+ },
43
+ ];
44
+
45
+ if (!isset ($ encoders [$ options ['integer.type ' ]])) {
46
+ throw new \InvalidArgumentException ('Invalid integer encoding type ' );
47
+ }
48
+
49
+ $ callback = $ encoders [$ options ['integer.type ' ]];
50
+
51
+ return $ callback ((int ) $ value , $ options );
52
+ }
26
53
27
- if ($ value === 1 << (PHP_INT_SIZE * 8 - 1 )) {
28
- $ string = sprintf ('(int)%s%s ' , $ options ['whitespace ' ] ? ' ' : '' , $ string );
54
+ public function encodeBinary ($ integer )
55
+ {
56
+ return sprintf ('%s0b%s ' , $ this ->sign ($ integer ), decbin (abs ($ integer )));
57
+ }
58
+
59
+ public function encodeOctal ($ integer )
60
+ {
61
+ return sprintf ('%s0%s ' , $ this ->sign ($ integer ), decoct (abs ($ integer )));
62
+ }
63
+
64
+ public function encodeDecimal ($ integer , $ options )
65
+ {
66
+ if ($ integer === 1 << (PHP_INT_SIZE * 8 - 1 )) {
67
+ return sprintf ('(int)%s%s ' , $ options ['whitespace ' ] ? ' ' : '' , $ integer );
68
+ }
69
+
70
+ return var_export ($ integer , true );
71
+ }
72
+
73
+ public function encodeHexadecimal ($ integer )
74
+ {
75
+ return sprintf ('%s0x%s ' , $ this ->sign ($ integer ), dechex (abs ($ integer )));
76
+ }
77
+
78
+ private function sign ($ integer )
79
+ {
80
+ if ($ integer < 0 ) {
81
+ return '- ' ;
29
82
}
30
83
31
- return $ string ;
84
+ return '' ;
32
85
}
33
86
}
0 commit comments