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