Skip to content

Commit 875fd82

Browse files
committed
#29 - Add JSON encoder
1 parent 10dd4e6 commit 875fd82

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

src/TgUtils/JSON.php

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
namespace TgUtils;
4+
5+
class JSON {
6+
7+
/**
8+
* Encodes a value after deep inspection for any values to be transformed.
9+
* These transformations are made:
10+
* \TgUtils\Date - transformed to ISO8601 string
11+
* \TgUtils\SelfJsonEncoder - transformed to according structure (using json_decode($mixed->json_encode))
12+
* any other object - deep inspected with get_object_vars() and transformed to \stdClass
13+
* array - deep inspected and transformed to arrays respecting keys
14+
* any other value - no transformation
15+
*
16+
* @param mixed $mixed - the value to be transformed
17+
* @param int $flags - see PHP json_encode() documentation
18+
* @param int $depth - see PHP json_encode() documentation
19+
* @return string - JSON representation of $mixed
20+
*/
21+
public static function encode($mixed, int $flags=0, int $depth=512) {
22+
return json_encode(self::transformForEncode($mixed), $flags, $depth);
23+
}
24+
25+
/**
26+
* Transforms a value recursively in order to detect dates and self-encoders.
27+
* These transformations are made:
28+
* \TgUtils\Date - transformed to ISO8601 string
29+
* \TgUtils\SelfJsonEncoder - transformed to according structure (using json_decode($mixed->json_encode))
30+
* any other object - deep inspected with get_object_vars() and transformed to \stdClass
31+
* array - deep inspected and transformed to arrays respecting keys
32+
* any other value - no transformation
33+
*
34+
* @param mixed $mixed - the value to be transformed
35+
* @return mixed - the transformed value
36+
*/
37+
public static function transformForEncode($mixed) {
38+
if (is_object($mixed)) {
39+
if (is_a($mixed, 'TgUtils\\Date')) {
40+
$mixed = $mixed->toISO8601(TRUE);
41+
} else if (is_a($mixed, 'TgUtils\\SelfJsonEncoder')) {
42+
$mixed = json_decode($mixed->json_encode());
43+
} else {
44+
$rc = new \stdClass;
45+
foreach (get_object_vars($mixed) AS $name => $value) {
46+
$rc->$name = self::transformForEncode($value);
47+
}
48+
$mixed = $rc;
49+
}
50+
} else if (is_array($mixed)) {
51+
$rc = array();
52+
foreach ($mixed AS $key => $value) {
53+
$rc[$key] = self::transformForEncode($value);
54+
}
55+
$mixed = $rc;
56+
}
57+
return $mixed;
58+
}
59+
60+
}

0 commit comments

Comments
 (0)