commit | author | age
|
90c639
|
1 |
<?php |
Z |
2 |
|
|
3 |
namespace app\core; |
|
4 |
|
|
5 |
class Serializer extends \yii\base\Component |
|
6 |
{ |
|
7 |
public function encode($value) |
|
8 |
{ |
|
9 |
return json_encode($value, JSON_UNESCAPED_UNICODE); |
|
10 |
} |
|
11 |
|
|
12 |
public function decode($value) |
|
13 |
{ |
|
14 |
$res = json_decode($value, true); |
|
15 |
if ($res === null) { |
|
16 |
if (json_last_error() == JSON_ERROR_NONE) { |
|
17 |
return $res; |
|
18 |
} |
|
19 |
if (json_last_error() != JSON_ERROR_SYNTAX) { |
|
20 |
$error = json_last_error_msg(); |
|
21 |
throw new \InvalidArgumentException("{$error}: `{$value}` cannot be decoded!"); |
|
22 |
} |
|
23 |
$res = unserialize($value); |
|
24 |
if ($res === false) { |
|
25 |
$value = preg_replace_callback( |
|
26 |
'/s:([0-9]+):\"(.*?)\";/', |
|
27 |
function ($matches) { |
|
28 |
return "s:" . strlen($matches[2]) . ':"' . $matches[2] . '";'; |
|
29 |
}, |
|
30 |
$value |
|
31 |
); |
|
32 |
$res = unserialize($value); |
|
33 |
if ($res === false) { |
|
34 |
throw new \InvalidArgumentException("`{$value}` cannot be unserialized!"); |
|
35 |
} |
|
36 |
} |
|
37 |
} |
|
38 |
if (!is_object($res) && !is_array($res)) { |
|
39 |
return $res; |
|
40 |
} |
|
41 |
return new \ArrayObject($res, \ArrayObject::ARRAY_AS_PROPS); |
|
42 |
} |
|
43 |
} |