-
Notifications
You must be signed in to change notification settings - Fork 19
/
JsonldContextGenerator.php
357 lines (324 loc) · 12.6 KB
/
JsonldContextGenerator.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
<?php
namespace Drupal\jsonld\ContextGenerator;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\rdf\RdfMappingInterface;
use Drupal\rdf\Entity\RdfMapping;
use Psr\Log\LoggerInterface;
/**
* A reliable JSON-LD @Context generation class.
*
* Class ContextGenerator.
*
* @package Drupal\jsonld\ContextGenerator
*/
class JsonldContextGenerator implements JsonldContextGeneratorInterface {
/**
* Constant Naming convention used to prefix name cache bins($cid)
*/
const CACHE_BASE_CID = 'jsonld:context';
/**
* Constant hook alter name.
*/
const FIELD_MAPPPINGS_HOOK = 'jsonld_field_mappings';
/**
* Injected EntityFieldManager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager = NULL;
/**
* Injected EntityTypeManager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager = NULL;
/**
* Injected EntityTypeBundle.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo = NULL;
/**
* Injected Cache implementation.
*
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
protected $cache;
/**
* Injected Logger Interface.
*
* @var \Psr\Log\LoggerInterface
* A logger instance.
*/
protected $logger;
/**
* Cached field type mappings.
*
* @var array
*/
protected $fieldMappings = [];
/**
* Constructs a ContextGenerator object.
*
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
* The language manager.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
* The Entity Type Manager.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* Caching Backend.
* @param \Psr\Log\LoggerInterface $logger_channel
* Our Logging Channel.
*/
public function __construct(EntityFieldManagerInterface $entity_field_manager, EntityTypeBundleInfoInterface $bundle_info, EntityTypeManagerInterface $entity_manager, CacheBackendInterface $cache_backend, LoggerInterface $logger_channel) {
$this->entityFieldManager = $entity_field_manager;
$this->entityTypeManager = $entity_manager;
$this->bundleInfo = $bundle_info;
$this->cache = $cache_backend;
$this->logger = $logger_channel;
}
/**
* {@inheritdoc}
*/
public function getContext($ids) {
$cid = JsonldContextGenerator::CACHE_BASE_CID . $ids;
$cache = $this->cache->get($cid);
$data = '';
if (!$cache) {
$rdfMapping = RdfMapping::load($ids);
// Our whole chain of exceptions will never happen
// because RdfMapping:load returns NULL on non existance
// Which forces me to check for it
// and don't even call writeCache on missing
// Solution, throw also one here.
if ($rdfMapping) {
$data = $this->writeCache($rdfMapping, $cid);
}
else {
$msg = t("Can't generate JSON-LD Context for @ids without RDF Mapping present.",
['@ids' => $ids]);
$this->logger->warning("@msg",
[
'@msg' => $msg,
]);
throw new \Exception($msg);
}
}
else {
$data = $cache->data;
}
return $data;
}
/**
* {@inheritdoc}
*/
public function generateContext(RdfMappingInterface $rdfMapping) {
// @todo we will need to use \Drupal\Core\Field\FieldDefinitionInterface
// a lot to be able to create/frame/discern drupal bundles based on JSON-LD
// So keep an eye on that definition.
$allRdfNameSpaces = rdf_get_namespaces();
// This one will become our return value.
$jsonLdContextArray['@context'] = [];
// Temporary array to keep track of our used namespaces and props.
$theAccumulator = [];
$bundle_rdf_mappings = $rdfMapping->getPreparedBundleMapping();
$drupal_types = $this->entityBundleIdsSplitter($rdfMapping->id());
$entity_type_id = $drupal_types['entityTypeId'];
$bundle = $drupal_types['bundleId'];
// If we don't have rdf:type(s) for this bundle then it makes little
// sense to continue.
// This only generates an Exception if there is an
// rdfmapping object but has no rdf:type.
if (empty($bundle_rdf_mappings['types'])) {
$msg = t("Can't generate JSON-LD Context without at least one rdf:type for Entity type @entity_type, Bundle @bundle_name combo.",
['@entity_type' => $entity_type_id, ' @bundle_name' => $bundle]);
$this->logger->warning("@msg",
[
'@msg' => $msg,
]);
throw new \Exception($msg);
}
/* We have a lot of assumptions here (rdf module is strange)
a) xsd and other utility namespaces are in place
b) the user knows what/how rdf mapping works and does it right
c) that if a field's mapping_type is "rel" or "rev" and datatype is
not defined, then '@type' is uncertain.
d) that mapping back and forward is 1 to 1.
Drupal allows multiple fields to be mapped to a same rdf prop
but that does not scale back. If drupal gets an input with a list
of values for a given property, we would never know in which Drupal
fields we should put those values. it's the many to one,
one to many reduction problem made worst by the abstraction of
fields being containers of mappings and not rdf properties. */
// Only care for those mappings that point to bundled or base fields.
// First our bundled fields.
foreach ($this->entityFieldManager->getFieldDefinitions($entity_type_id, $bundle) as $bundleFieldName => $fieldDefinition) {
$field_context = $this->getFieldsRdf($rdfMapping, $bundleFieldName, $fieldDefinition, $allRdfNameSpaces);
$theAccumulator = array_merge($field_context, $theAccumulator);
}
// And then our Base fields.
foreach ($this->entityFieldManager->getBaseFieldDefinitions($entity_type_id) as $baseFieldName => $fieldDefinition) {
$field_context = $this->getFieldsRdf($rdfMapping, $baseFieldName, $fieldDefinition, $allRdfNameSpaces);
$theAccumulator = array_merge($field_context, $theAccumulator);
}
$theAccumulator = array_filter($theAccumulator);
$jsonLdContextArray['@context'] = $theAccumulator;
return json_encode($jsonLdContextArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
/**
* {@inheritdoc}
*/
public function getFieldsRdf(RdfMappingInterface $rdfMapping, $field_name, FieldDefinitionInterface $fieldDefinition, array $allRdfNameSpaces) {
$termDefinition = [];
$fieldContextFragment = [];
$fieldRDFMapping = $rdfMapping->getPreparedFieldMapping($field_name);
if (!empty($fieldRDFMapping)) {
// If one ore more properties, all will share same datatype so
// get that before iterating.
// First get our defaults, no-user or config based input.
$default_field_term_mapping = $this->getTermContextFromField($fieldDefinition->getType());
// Now we start overriding from config entity defined mappings.
// Assume all non defined mapping types as "property".
$reltype = isset($fieldRDFMapping['mapping_type']) ? $fieldRDFMapping['mapping_type'] : 'property';
if (isset($fieldRDFMapping['datatype']) && ($reltype == 'property')) {
$termDefinition = ['@type' => $fieldRDFMapping['datatype']];
}
if (!isset($fieldRDFMapping['datatype']) && ($reltype != 'property')) {
$termDefinition = ['@type' => '@id'];
}
// This should respect user provided mapping and fill rest with defaults.
$termDefinition = $termDefinition + $default_field_term_mapping;
// Now iterate over all properties for this field
// trying to parse them as compact IRI.
foreach ($fieldRDFMapping['properties'] as $property) {
$compactedDefinition = $this->parseCompactedIri($property);
if ($compactedDefinition['prefix'] != NULL) {
// Check if the namespace prefix exists.
if (array_key_exists($compactedDefinition['prefix'], $allRdfNameSpaces)) {
// Just overwrite as many times as needed,
// still faster than checking if
// it's there in the first place.
$fieldContextFragment[$compactedDefinition['prefix']] = $allRdfNameSpaces[$compactedDefinition['prefix']];
$fieldContextFragment[$property] = $termDefinition;
}
}
}
}
return $fieldContextFragment;
}
/**
* Writes JSON-LD @context cache per Entity_type bundle combo.
*
* @param \Drupal\rdf\RdfMappingInterface $rdfMapping
* Rdf mapping object.
* @param string $cid
* Name of the cache bin to use.
*
* @return string
* A json encoded string for the processed JSON-LD @context
*/
protected function writeCache(RdfMappingInterface $rdfMapping, $cid) {
// This is how an empty json encoded @context looks like.
$data = json_encode(['@context' => ''], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
try {
$data = $this->generateContext($rdfMapping);
$this->cache->set($cid, $data, Cache::PERMANENT, $rdfMapping->getCacheTagsToInvalidate());
}
catch (\Exception $e) {
$this->logger->warning("@msg",
[
'@msg' => $e->getMessage(),
]);
}
return $data;
}
/**
* Absurdly simple exploder for a joint entityType and Bundle ids string.
*
* @param string $ids
* A string with containing entity id and bundle joined by a dot.
*
* @return array
* And array with the entity type and the bundle id
*/
protected function entityBundleIdsSplitter($ids) {
list($entity_type_id, $bundle_id) = explode(".", $ids, 2);
return ['entityTypeId' => $entity_type_id, 'bundleId' => $bundle_id];
}
/**
* Parses and IRI, checks if it is complaint with compacted IRI definition.
*
* Assumes this notion of compact IRI/similar to CURIE
* http://json-ld.org/spec/ED/json-ld-syntax/20120522/#dfn-prefix.
*
* @param string $iri
* IRIs are strings.
*
* @return array
* If $iri is a compacted iri, prefix and term as separate
* array members, if not, unmodified $iri in term position
* and null prefix.
*/
protected function parseCompactedIri($iri) {
// As naive as it gets.
list($prefix, $rest) = array_pad(explode(":", $iri, 2), 2, '');
if ((substr($rest, 0, 2) == "//") || ($prefix == $iri)) {
// Means this was never a compacted IRI.
return ['prefix' => NULL, 'term' => $iri];
}
return ['prefix' => $prefix, 'term' => $rest];
}
/**
* Naive approach on Drupal field to JSON-LD type mapping.
*
* @todo Would be fine to have this definitions in an
* configEntity way in the future.
*
* @param string $field_type
* As provided by \Drupal\Core\Field\FieldDefinitionInterface::getType().
*
* @return array
* A json-ld term definition if there is a match
* or array("@type" => "xsd:string") in case of no match.
*/
protected function getTermContextFromField($field_type) {
// Be aware that drupal field definitions can be complex.
// e.g text_with_summary has a text, a summary, a number of lines, etc
// we are only dealing with the resulting ->value() of all this separate
// pieces and mapping only that as a whole.
// Default mapping to return in case no $field_type matches
// field_mappings array keys.
$default_mapping = [
"@type" => "xsd:string",
];
// Only load mappings from hooks if we haven't done it
// yet for this instance.
if (empty($this->fieldMappings)) {
// Cribbed from rdf module's rdf_get_namespaces.
foreach (\Drupal::moduleHandler()->getImplementations(self::FIELD_MAPPPINGS_HOOK) as $module) {
$function = $module . '_' . self::FIELD_MAPPPINGS_HOOK;
foreach ($function() as $field => $mapping) {
if (array_key_exists($field, $this->fieldMappings)) {
$this->logger->warning(
t('Tried to map @field_type to @new_type, but @field_type is already mapped to @orig_type.', [
'@field_type' => $field,
'@new_type' => $mapping['@type'],
'@orig_type' => $this->fieldMappings[$field]['@type'],
])
);
}
else {
$this->fieldMappings[$field] = $mapping;
}
}
}
}
return array_key_exists($field_type, $this->fieldMappings) ? $this->fieldMappings[$field_type] : $default_mapping;
}
}