|
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
|
|
|
*/ |
|
30
|
|
|
public function jsonLDSerialize(string $context=self::DEFAULT_CONTEXT) |
|
31
|
|
|
{ |
|
32
|
|
|
$json = [ ]; |
|
33
|
|
|
|
|
34
|
|
|
foreach ($this as $key => $value) { |
|
|
|
|
|
|
35
|
|
|
if (isset($value)) { |
|
36
|
|
|
if ($value instanceof PrettyJsonSerializable) { |
|
37
|
|
|
$value = $value->jsonLDSerialize(''); |
|
38
|
|
|
} elseif (is_array($value) and !count(array_filter(array_keys($value), 'is_string'))) { |
|
|
|
|
|
|
39
|
|
|
$a = []; |
|
40
|
|
|
foreach ($value as $m) { |
|
41
|
|
|
if ($m instanceof PrettyJsonSerializable) { |
|
42
|
|
|
$m = $m->jsonLDSerialize(''); |
|
43
|
|
|
} |
|
44
|
|
|
$a[] = $m; |
|
45
|
|
|
} |
|
46
|
|
|
$value = $a; |
|
47
|
|
|
} |
|
48
|
|
|
$json[$key] = $value; |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
if ($context) { |
|
53
|
|
|
$json['@context'] = $context; |
|
54
|
|
|
$types = defined(get_called_class().'::TYPES') ? static::TYPES : []; |
|
55
|
|
|
if (property_exists($this, 'type') and count($types)) { |
|
|
|
|
|
|
56
|
|
|
if (isset($json['type'])) { |
|
57
|
|
|
if (empty(array_intersect($json['type'], $types))) { |
|
58
|
|
|
array_unshift($json['type'], $types[0]); |
|
59
|
|
|
} |
|
60
|
|
|
} else { |
|
61
|
|
|
$json['type'] = [$types[0]]; |
|
62
|
|
|
} |
|
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
|
|
|
|