-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRisonEncoder.php
More file actions
99 lines (76 loc) · 2.71 KB
/
RisonEncoder.php
File metadata and controls
99 lines (76 loc) · 2.71 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace Kunststube\Rison;
require_once __DIR__ . DIRECTORY_SEPARATOR . 'Rison.php';
class RisonEncoder extends Rison {
protected $value = null;
protected $encoders = array();
public function __construct($value) {
$this->value = $value;
$this->init();
}
protected function init() {
$this->encoders = array(
'boolean' => array($this, 'encodeBoolean'),
'integer' => array($this, 'encodeInteger'),
'double' => array($this, 'encodeDouble'),
'string' => array($this, 'encodeString'),
'array' => array($this, 'encodeArray'),
'object' => array($this, 'encodeObject'),
'resource' => array($this, 'encodeResource'),
'null' => array($this, 'encodeNull'),
);
$this->idOkRegex = "/^[^{$this->notIdstart}{$this->notIdchar}][^{$this->notIdchar}]*\$/";
}
public function encode() {
return $this->encodeValue($this->value);
}
protected function encodeValue($value) {
$type = strtolower(gettype($value));
if (!isset($this->encoders[$type])) {
throw new \InvalidArgumentException("Cannot encode value of type $type");
}
return call_user_func($this->encoders[$type], $value);
}
protected function encodeBoolean($boolean) {
return $boolean ? '!t' : '!f';
}
protected function encodeNull($null) {
return '!n';
}
protected function encodeInteger($integer) {
return $integer;
}
protected function encodeDouble($double) {
return strtolower(str_replace('+', '', (string)$double));
}
protected function encodeResource($resource) {
throw new \InvalidArgumentException("Cannot encode resource $resource");
}
protected function encodeString($string) {
if ($string === '') {
return "''";
}
if (preg_match($this->idOkRegex, $string)) {
return $string;
}
$string = preg_replace("/['!]/", '!$0', $string);
return "'$string'";
}
protected function encodeArray(array $array) {
$keys = array_keys($array);
$isArray = range(0, count($keys) - 1) === $keys;
if (!$isArray) {
return $this->encodeObject($array);
}
return '!(' . join(',', array_map(array($this, 'encodeValue'), $array)) . ')';
}
protected function encodeObject($object) {
$object = (array)$object;
ksort($object);
$encoded = array();
foreach ($object as $key => $value) {
$encoded[] = $this->encodeValue($key) . ':' . $this->encodeValue($value);
}
return '(' . join(',', $encoded) . ')';
}
}