1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace JSKOS; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Provide consistent JSON(-LD) serializing. |
7
|
|
|
*/ |
8
|
|
|
abstract class PrettyJsonSerializable implements \JsonSerializable |
9
|
|
|
{ |
10
|
|
|
const DEFAULT_CONTEXT = 'https://gbv.github.io/jskos/context.json'; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Returns data which should be serialized to JSON. |
14
|
|
|
* |
15
|
|
|
* Delegates to jsonLDSerialize which can be called with a JSON-LD context URL. |
16
|
|
|
*/ |
17
|
|
|
public function jsonSerialize() |
18
|
|
|
{ |
19
|
|
|
return $this->jsonLDSerialize(); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Returns data which should be serialized to JSON. |
24
|
|
|
* |
25
|
|
|
* Include all non-null members and the JSON-LD context (`@context`). |
26
|
|
|
* Keys are sorted by Unicode codepoint for stable output. |
27
|
|
|
* |
28
|
|
|
* @param string $context optional JSON-LD context URL. Use empty string to omit. |
29
|
|
|
* @param bool $types include default type URIs. |
30
|
|
|
*/ |
31
|
|
|
public function jsonLDSerialize(string $context = self::DEFAULT_CONTEXT, bool $types = null) |
32
|
|
|
{ |
33
|
|
|
$json = []; |
34
|
|
|
|
35
|
|
|
foreach ($this as $key => $value) { |
36
|
|
|
if (isset($value)) { |
37
|
|
|
if ($value instanceof PrettyJsonSerializable) { |
38
|
|
|
$value = $value->jsonLDSerialize('', false); |
39
|
|
|
} elseif (is_array($value) and !count(array_filter(array_keys($value), 'is_string'))) { |
40
|
|
|
$a = []; |
41
|
|
|
foreach ($value as $m) { |
42
|
|
|
if ($m instanceof PrettyJsonSerializable) { |
43
|
|
|
$m = $m->jsonLDSerialize('', false); |
44
|
|
|
} |
45
|
|
|
$a[] = $m; |
46
|
|
|
} |
47
|
|
|
$value = $a; |
48
|
|
|
} |
49
|
|
|
$json[$key] = $value; |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
# don't serialize implicitly deriveable types for brevity |
54
|
|
|
if ($context) { |
55
|
|
|
$json['@context'] = $context; |
56
|
|
|
} |
57
|
|
|
if ($types === null) { |
58
|
|
|
$types = (bool)$context; |
59
|
|
|
} |
60
|
|
|
if (!$types && count($json['type'] ?? []) == 1 && count(static::TYPES)) { |
61
|
|
|
if ($json['type'][0] == static::TYPES[0]) { |
62
|
|
|
unset($json['type']); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
ksort($json); |
67
|
|
|
return $json; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Serialize to JSON in string context. |
72
|
|
|
*/ |
73
|
|
|
public function __toString() |
74
|
|
|
{ |
75
|
|
|
return json_encode($this, JSON_UNESCAPED_SLASHES); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Serialize to pretty-printed JSON. |
80
|
|
|
*/ |
81
|
|
|
public function json() |
82
|
|
|
{ |
83
|
|
|
return json_encode($this, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|