-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtnetstring.php
101 lines (85 loc) · 2.38 KB
/
tnetstring.php
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
100
101
<?php
/**
* This file is part of the TNetstring project and is copyright
*
* (c) 2011-2016 Sam Smith <git@samsmith.io>.
*
* Please refer the to LICENSE file that was distributed with this source code
* for the full copyright and license information.
*/
$__tnetstring_last_error = null;
use Phuedx\TNetstring\Codec;
/**
* Encodes the value as a tagged netstring.
*
* @see \Phuedx\TNetstring\Codec#encode
*
* @param mixed $value
* @return string|null The encoded tagged netstring. If an error occurs during
* encoding, then `null` is returned. An error *should* only occur if the
* value can't be converted to a string, e.g. the value is a resource.
*/
function tnetstring_encode($value)
{
global $__tnetstring_last_error;
try {
return __tnetstring_codec()->encode($value);
} catch (Exception $e) {
$__tnetstring_last_error = $e->getMessage();
return null;
}
}
/**
* Decodes the value or values from the tagged netstring.
*
* Note well that if the tagged netstring is a single encoded value, then that
* value will be returned. If the tagged netstring is a collection of encoded
* values those values will be returned as an array.
*
* @see \Phuedx\TNetstring\Codec#decode
*
* @param string $tnetstring
* @return mixed The decoded value or values. If an error occurs during
* decoding, then `null` is returned. An error *should* only occur if either
* the tagged netstring is empty or incorrectly encoded.
*/
function tnetstring_decode($tnetstring)
{
global $__tnetstring_last_error;
try {
return __tnetstring_codec()->decode($tnetstring);
} catch (Exception $e) {
$__tnetstring_last_error = $e->getMessage();
return null;
}
}
function __tnetstring_codec()
{
static $codec;
if (! $codec) {
$codec = new Codec();
}
return $codec;
}
/**
* Gets the message associated with the last error that occurred during encoding
* or decoding, if one occurred.
*
* @return string|null
*/
function tnetstring_last_error()
{
global $__tnetstring_last_error;
return $__tnetstring_last_error;
}
/**
* Clears the message associated with the last error that occurred during
* encoding or decoding, if one occurred.
*
* @return null
*/
function tnetstring_clear_last_error()
{
global $__tnetstring_last_error;
$__tnetstring_last_error = null;
}