forked from lanthaler/JsonLD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Processor.php
2973 lines (2536 loc) · 111 KB
/
Processor.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* (c) Markus Lanthaler <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ML\JsonLD;
use stdClass as JsonObject;
use ML\JsonLD\Exception\JsonLdException;
use ML\JsonLD\Exception\InvalidQuadException;
use ML\IRI\IRI;
/**
* Processor processes JSON-LD documents as specified by the JSON-LD
* specification.
*
* @author Markus Lanthaler <[email protected]>
*/
class Processor
{
/** Timeout for retrieving remote documents in seconds */
const REMOTE_TIMEOUT = 10;
/** Maximum number of recursion that are allowed to resolve an IRI */
const CONTEXT_MAX_IRI_RECURSIONS = 10;
/**
* @var array A list of all defined keywords
*/
private static $keywords = array('@context', '@id', '@value', '@language', '@type',
'@container', '@list', '@set', '@graph', '@reverse',
'@base', '@vocab', '@index', '@null');
// TODO Introduce @null supported just for framing
/**
* @var array Framing options keywords
*/
private static $framingKeywords = array('@explicit', '@default', '@embed',
//'@omitDefault', // TODO Is this really needed?
'@embedChildren'); // TODO How should this be called?
// TODO Add @preserve, @null?? Update spec keyword list
/**
* @var IRI The base IRI
*/
private $baseIri = null;
/**
* Compact arrays with just one element to a scalar
*
* If set to true, arrays holding just one element are compacted to
* scalars, otherwise the arrays are kept as arrays.
*
* @var bool
*/
private $compactArrays;
/**
* Optimize compacted output
*
* If set to true, the processor is free to optimize the result to produce
* an even compacter representation than the algorithm described by the
* official JSON-LD specification.
*
* @var bool
*/
private $optimize;
/**
* Use native types when converting from RDF
*
* If set to true, the processor will try to convert datatyped literals
* to native types instead of using the expanded object form when
* converting from RDF. xsd:boolean values will be converted to booleans
* whereas xsd:integer and xsd:double values will be converted to numbers.
*
* @var bool
*/
private $useNativeTypes;
/**
* Use rdf:type instead of \@type when converting from RDF
*
* If set to true, the JSON-LD processor will use the expanded rdf:type
* IRI as the property instead of \@type when converting from RDF.
*
* @var bool
*/
private $useRdfType;
/**
* Produce generalized RDF
*
* Unless set to true, triples/quads with a blank node predicate are
* dropped when converting to RDF.
*
* @var bool
*/
private $generalizedRdf;
/**
* @var array Blank node map
*/
private $blankNodeMap = array();
/**
* @var integer Blank node counter
*/
private $blankNodeCounter = 0;
/**
* @var DocumentFactoryInterface The factory to create new documents
*/
private $documentFactory = null;
/**
* @var DocumentLoaderInterface The document loader
*/
private $documentLoader = null;
/**
* Constructor
*
* The options parameter must be passed and all off the following properties
* have to be set:
*
* <dl>
* <dl>base</dl>
* <dt>The base IRI.</dt>
*
* <dl>compactArrays</dl>
* <dt>If set to true, arrays holding just one element are compacted
* to scalars, otherwise the arrays are kept as arrays.</dt>
*
* <dl>optimize</dl>
* <dt>If set to true, the processor is free to optimize the result to
* produce an even compacter representation than the algorithm
* described by the official JSON-LD specification.</dt>
*
* <dl>useNativeTypes</dl>
* <dt>If set to true, the processor will try to convert datatyped
* literals to native types instead of using the expanded object form
* when converting from RDF. <em>xsd:boolean</em> values will be
* converted to booleans whereas <em>xsd:integer</em> and
* <em>xsd:double</em> values will be converted to numbers.</dt>
*
* <dl>useRdfType</dl>
* <dt>If set to true, the JSON-LD processor will use the expanded
* <em>rdf:type</em> IRI as the property instead of <em>@type</em>
* when converting from RDF.</dt>
* </dl>
*
* @param JsonObject $options Options to configure the various algorithms.
*/
public function __construct($options)
{
$this->baseIri = new IRI($options->base);
$this->compactArrays = (bool) $options->compactArrays;
$this->optimize = (bool) $options->optimize;
$this->useNativeTypes = (bool) $options->useNativeTypes;
$this->useRdfType = (bool) $options->useRdfType;
$this->generalizedRdf = (bool) $options->produceGeneralizedRdf;
$this->documentFactory = $options->documentFactory;
$this->documentLoader = $options->documentLoader;
}
/**
* Parses a JSON-LD document to a PHP value
*
* @param string $document A JSON-LD document.
*
* @return mixed A PHP value.
*
* @throws JsonLdException If the JSON-LD document is not valid.
*/
public static function parse($document)
{
if (function_exists('mb_detect_encoding') &&
(false === mb_detect_encoding($document, 'UTF-8', true))) {
throw new JsonLdException(
JsonLdException::LOADING_DOCUMENT_FAILED,
'The JSON-LD document does not appear to be valid UTF-8.'
);
}
$data = json_decode($document, false, 512);
switch (json_last_error()) {
case JSON_ERROR_NONE:
break; // no error
case JSON_ERROR_DEPTH:
throw new JsonLdException(
JsonLdException::LOADING_DOCUMENT_FAILED,
'The maximum stack depth has been exceeded.'
);
case JSON_ERROR_STATE_MISMATCH:
throw new JsonLdException(
JsonLdException::LOADING_DOCUMENT_FAILED,
'Invalid or malformed JSON.'
);
case JSON_ERROR_CTRL_CHAR:
throw new JsonLdException(
JsonLdException::LOADING_DOCUMENT_FAILED,
'Control character error (possibly incorrectly encoded).'
);
case JSON_ERROR_SYNTAX:
throw new JsonLdException(
JsonLdException::LOADING_DOCUMENT_FAILED,
'Syntax error, malformed JSON.'
);
case JSON_ERROR_UTF8:
throw new JsonLdException(
JsonLdException::LOADING_DOCUMENT_FAILED,
'Malformed UTF-8 characters (possibly incorrectly encoded).'
);
default:
throw new JsonLdException(
JsonLdException::LOADING_DOCUMENT_FAILED,
'Unknown error while parsing JSON.'
);
}
return (empty($data)) ? null : $data;
}
/**
* Parses a JSON-LD document and returns it as a Document
*
* @param array|JsonObject $input The JSON-LD document to process.
*
* @return Document The parsed JSON-LD document.
*
* @throws JsonLdException If the JSON-LD input document is invalid.
*/
public function getDocument($input)
{
$nodeMap = new JsonObject();
$nodeMap->{'-' . JsonLD::DEFAULT_GRAPH} = new JsonObject();
$this->generateNodeMap($nodeMap, $input);
// We need to keep track of blank nodes as they are renamed when
// inserted into the Document
$nodes = array();
if (null === $this->documentFactory) {
$this->documentFactory = new DefaultDocumentFactory();
}
$document = $this->documentFactory->createDocument($this->baseIri);
foreach ($nodeMap as $graphName => &$nodes) {
$graphName = substr($graphName, 1);
if (JsonLD::DEFAULT_GRAPH === $graphName) {
$graph = $document->getGraph();
} else {
$graph = $document->createGraph($graphName);
}
foreach ($nodes as $id => &$item) {
$node = $graph->createNode($item->{'@id'}, true);
unset($item->{'@id'});
// Process node type as it needs to be handled differently than
// other properties
// TODO Could this be avoided by enforcing rdf:type instead of @type?
if (property_exists($item, '@type')) {
foreach ($item->{'@type'} as $type) {
$node->addType($graph->createNode($type), true);
}
unset($item->{'@type'});
}
foreach ($item as $property => $values) {
foreach ($values as $value) {
if (property_exists($value, '@value')) {
$node->addPropertyValue($property, Value::fromJsonLd($value));
} elseif (property_exists($value, '@id')) {
$node->addPropertyValue(
$property,
$graph->createNode($value->{'@id'}, true)
);
} else {
// TODO Handle lists
throw new \Exception('Lists are not supported by getDocument() yet');
}
}
}
}
}
unset($nodeMap);
return $document;
}
/**
* Expands a JSON-LD document
*
* @param mixed $element A JSON-LD element to be expanded.
* @param array $activectx The active context.
* @param null|string $activeprty The active property.
* @param boolean $frame True if a frame is being expanded, otherwise false.
*
* @return mixed The expanded document.
*
* @throws JsonLdException
*/
public function expand(&$element, $activectx = array(), $activeprty = null, $frame = false)
{
if (is_scalar($element)) {
if ((null === $activeprty) || ('@graph' === $activeprty)) {
$element = null;
} else {
$element = $this->expandValue($element, $activectx, $activeprty);
}
return;
}
if (null === $element) {
return;
}
if (is_array($element)) {
$result = array();
foreach ($element as &$item) {
$this->expand($item, $activectx, $activeprty, $frame);
// Check for lists of lists
if (('@list' === $this->getPropertyDefinition($activectx, $activeprty, '@container')) ||
('@list' === $activeprty)) {
if (is_array($item) || (is_object($item) && property_exists($item, '@list'))) {
throw new JsonLdException(
JsonLdException::LIST_OF_LISTS,
"List of lists detected in property \"$activeprty\".",
$element
);
}
}
if (is_array($item)) {
$result = array_merge($result, $item);
} elseif (null !== $item) {
$result[] = $item;
}
}
$element = $result;
return;
}
// Otherwise it's an object. Process its local context if available
if (property_exists($element, '@context')) {
$this->processContext($element->{'@context'}, $activectx);
unset($element->{'@context'});
}
$properties = get_object_vars($element);
ksort($properties);
$element = new JsonObject();
foreach ($properties as $property => $value) {
$expProperty = $this->expandIri($property, $activectx, false, true);
// Make sure to keep framing keywords if a frame is being expanded
if ($frame && in_array($expProperty, self::$framingKeywords)) {
// and that the default value is expanded
if ('@default' === $expProperty) {
$this->expand($value, $activectx, $activeprty, $frame);
}
self::setProperty($element, $expProperty, $value, JsonLdException::COLLIDING_KEYWORDS);
continue;
}
if (in_array($expProperty, self::$keywords)) {
if ('@reverse' === $activeprty) {
throw new JsonLdException(
JsonLdException::INVALID_REVERSE_PROPERTY_MAP,
'No keywords or keyword aliases are allowed in @reverse-maps, found ' . $expProperty
);
}
$this->expandKeywordValue($element, $activeprty, $expProperty, $value, $activectx, $frame);
continue;
} elseif (false === strpos($expProperty, ':')) {
// the expanded property is neither a keyword nor an IRI
continue;
}
$propertyContainer = $this->getPropertyDefinition($activectx, $property, '@container');
if (is_object($value) && in_array($propertyContainer, array('@language', '@index'))) {
$result = array();
$value = (array) $value; // makes it easier to order the key-value pairs
ksort($value);
if ('@language' === $propertyContainer) {
foreach ($value as $key => $val) {
// TODO Make sure key is a valid language tag
if (false === is_array($val)) {
$val = array($val);
}
foreach ($val as $item) {
if (false === is_string($item)) {
throw new JsonLdException(
JsonLdException::INVALID_LANGUAGE_MAP_VALUE,
"Detected invalid value in $property->$key: it must be a string as it " .
"is part of a language map.",
$item
);
}
$result[] = (object) array(
'@value' => $item,
'@language' => strtolower($key)
);
}
}
} else {
// @container: @index
foreach ($value as $key => $val) {
if (false === is_array($val)) {
$val = array($val);
}
$this->expand($val, $activectx, $property, $frame);
foreach ($val as $item) {
if (false === property_exists($item, '@index')) {
$item->{'@index'} = $key;
}
$result[] = $item;
}
}
}
$value = $result;
} else {
$this->expand($value, $activectx, $property, $frame);
}
// Remove properties with null values
if (null === $value) {
continue;
}
// If property has an @list container and value is not yet an
// expanded @list-object, transform it to one
if (('@list' === $propertyContainer) &&
((false === is_object($value) || (false === property_exists($value, '@list'))))) {
if (false === is_array($value)) {
$value = array($value);
}
$obj = new JsonObject();
$obj->{'@list'} = $value;
$value = $obj;
}
$target = $element;
if ($this->getPropertyDefinition($activectx, $property, '@reverse')) {
if (false === property_exists($target, '@reverse')) {
$target->{'@reverse'} = new JsonObject();
}
$target = $target->{'@reverse'};
if (false === is_array($value)) {
$value = array($value);
}
foreach ($value as $val) {
if (property_exists($val, '@value') || property_exists($val, '@list')) {
throw new JsonLdException(
JsonLdException::INVALID_REVERSE_PROPERTY_VALUE,
'Detected invalid value in @reverse-map (only nodes are allowed',
$val
);
}
}
}
self::mergeIntoProperty($target, $expProperty, $value, true);
}
// All properties have been processed. Make sure the result is valid
// and optimize it where possible
$numProps = count(get_object_vars($element));
// Remove free-floating nodes
if ((false === $frame) && ((null === $activeprty) || ('@graph' === $activeprty)) &&
(((0 === $numProps) || property_exists($element, '@value') || property_exists($element, '@list') ||
((1 === $numProps) && property_exists($element, '@id'))))) {
$element = null;
return;
}
// Indexes are allowed everywhere
if (property_exists($element, '@index')) {
$numProps--;
}
if (property_exists($element, '@value')) {
$numProps--; // @value
if (property_exists($element, '@language')) {
if (false === $frame) {
if (false === is_string($element->{'@language'})) {
throw new JsonLdException(
JsonLdException::INVALID_LANGUAGE_TAGGED_STRING,
'Invalid value for @language detected (must be a string).',
$element
);
}
if (false === is_string($element->{'@value'})) {
throw new JsonLdException(
JsonLdException::INVALID_LANGUAGE_TAGGED_VALUE,
'Only strings can be language tagged.',
$element
);
}
}
$numProps--;
} elseif (property_exists($element, '@type')) {
if ((false === $frame) && ((false === is_string($element->{'@type'})) ||
(false === strpos($element->{'@type'}, ':')) ||
('_:' === substr($element->{'@type'}, 0, 2)))) {
throw new JsonLdException(
JsonLdException::INVALID_TYPED_VALUE,
'Invalid value for @type detected (must be an IRI).',
$element
);
}
$numProps--;
}
if ($numProps > 0) {
throw new JsonLdException(
JsonLdException::INVALID_VALUE_OBJECT,
'Detected an invalid @value object.',
$element
);
} elseif (null === $element->{'@value'}) {
// object has just an @value property that is null, can be replaced with that value
$element = $element->{'@value'};
}
return;
}
// Not an @value object, make sure @type is an array
if (property_exists($element, '@type') && (false === is_array($element->{'@type'}))) {
$element->{'@type'} = array($element->{'@type'});
}
if (($numProps > 1) && ((property_exists($element, '@list') || property_exists($element, '@set')))) {
throw new JsonLdException(
JsonLdException::INVALID_SET_OR_LIST_OBJECT,
'An object with a @list or @set property can\'t contain other properties.',
$element
);
} elseif (property_exists($element, '@set')) {
// @set objects can be optimized away as they are just syntactic sugar
$element = $element->{'@set'};
} elseif (($numProps === 1) && (false === $frame) && property_exists($element, '@language')) {
// if there's just @language and nothing else and we are not expanding a frame, drop whole object
$element = null;
}
}
/**
* Expands the value of a keyword
*
* @param JsonObject $element The object this property-value pair is part of.
* @param string $activeprty The active property.
* @param string $keyword The keyword whose value is being expanded.
* @param mixed $value The value to expand.
* @param array $activectx The active context.
* @param boolean $frame True if a frame is being expanded, otherwise false.
*
* @throws JsonLdException
*/
private function expandKeywordValue(&$element, $activeprty, $keyword, $value, $activectx, $frame)
{
// Ignore all null values except for @value as in that case it is
// needed to determine what @type means
if ((null === $value) && ('@value' !== $keyword)) {
return;
}
if ('@id' === $keyword) {
if (false === is_string($value)) {
throw new JsonLdException(
JsonLdException::INVALID_ID_VALUE,
'Invalid value for @id detected (must be a string).',
$element
);
}
$value = $this->expandIri($value, $activectx, true);
self::setProperty($element, $keyword, $value, JsonLdException::COLLIDING_KEYWORDS);
return;
}
if ('@type' === $keyword) {
if (is_string($value)) {
$value = $this->expandIri($value, $activectx, true, true);
self::setProperty($element, $keyword, $value, JsonLdException::COLLIDING_KEYWORDS);
return;
}
if (false === is_array($value)) {
$value = array($value);
}
$result = array();
foreach ($value as $item) {
if (is_string($item)) {
$result[] = $this->expandIri($item, $activectx, true, true);
} else {
if (false === $frame) {
throw new JsonLdException(
JsonLdException::INVALID_TYPE_VALUE,
"Invalid value for $keyword detected.",
$value
);
}
self::mergeIntoProperty($element, $keyword, $item);
}
}
// Don't keep empty arrays
if (count($result) >= 1) {
self::mergeIntoProperty($element, $keyword, $result, true);
}
}
if (('@value' === $keyword)) {
if (false === $frame) {
if ((null !== $value) && (false === is_scalar($value))) {
// we need to preserve @value: null to distinguish values form nodes
throw new JsonLdException(
JsonLdException::INVALID_VALUE_OBJECT_VALUE,
"Invalid value for @value detected (must be a scalar).",
$value
);
}
} elseif (false === is_array($value)) {
$value = array($value);
}
self::setProperty($element, $keyword, $value, JsonLdException::COLLIDING_KEYWORDS);
return;
}
if (('@language' === $keyword) || ('@index' === $keyword)) {
if (false === $frame) {
if (false === is_string($value)) {
throw ('@language' === $keyword)
? new JsonLdException(
JsonLdException::INVALID_LANGUAGE_TAGGED_STRING,
'@language must be a string',
$value
)
: new JsonLdException(
JsonLdException::INVALID_INDEX_VALUE,
'@index must be a string',
$value
);
}
} elseif (false === is_array($value)) {
$value = array($value);
}
self::setProperty($element, $keyword, $value, JsonLdException::COLLIDING_KEYWORDS);
return;
}
// TODO Optimize the following code, there's a lot of repetition, only the $activeprty param is changing
if ('@list' === $keyword) {
if ((null === $activeprty) || ('@graph' === $activeprty)) {
return;
}
$this->expand($value, $activectx, $activeprty, $frame);
if (false === is_array($value)) {
$value = array($value);
}
foreach ($value as $val) {
if (is_object($val) && property_exists($val, '@list')) {
throw new JsonLdException(JsonLdException::LIST_OF_LISTS, 'List of lists detected.', $element);
}
}
self::mergeIntoProperty($element, $keyword, $value, true);
return;
}
if ('@set' === $keyword) {
$this->expand($value, $activectx, $activeprty, $frame);
self::mergeIntoProperty($element, $keyword, $value, true);
return;
}
if ('@reverse' === $keyword) {
if (false === is_object($value)) {
throw new JsonLdException(
JsonLdException::INVALID_REVERSE_VALUE,
'Detected invalid value for @reverse (must be an object).',
$value
);
}
$this->expand($value, $activectx, $keyword, $frame);
// Do not create @reverse-containers inside @reverse containers
if (property_exists($value, $keyword)) {
foreach (get_object_vars($value->{$keyword}) as $prop => $val) {
self::mergeIntoProperty($element, $prop, $val, true);
}
unset($value->{$keyword});
}
$value = get_object_vars($value);
if ((count($value) > 0) && (false === property_exists($element, $keyword))) {
$element->{$keyword} = new JsonObject();
}
foreach ($value as $prop => $val) {
foreach ($val as $v) {
if (property_exists($v, '@value') || property_exists($v, '@list')) {
throw new JsonLdException(
JsonLdException::INVALID_REVERSE_PROPERTY_VALUE,
'Detected invalid value in @reverse-map (only nodes are allowed',
$v
);
}
self::mergeIntoProperty($element->{$keyword}, $prop, $v, true);
}
}
return;
}
if ('@graph' === $keyword) {
$this->expand($value, $activectx, $keyword, $frame);
self::mergeIntoProperty($element, $keyword, $value, true);
return;
}
}
/**
* Expands a scalar value
*
* @param mixed $value The value to expand.
* @param array $activectx The active context.
* @param string $activeprty The active property.
*
* @return JsonObject The expanded value.
*/
private function expandValue($value, $activectx, $activeprty)
{
$def = $this->getPropertyDefinition($activectx, $activeprty);
$result = new JsonObject();
if ('@id' === $def['@type']) {
$result->{'@id'} = $this->expandIri($value, $activectx, true);
} elseif ('@vocab' === $def['@type']) {
$result->{'@id'} = $this->expandIri($value, $activectx, true, true);
} else {
$result->{'@value'} = $value;
if (isset($def['@type'])) {
$result->{'@type'} = $def['@type'];
} elseif (isset($def['@language']) && is_string($result->{'@value'})) {
$result->{'@language'} = $def['@language'];
}
}
return $result;
}
/**
* Expands a JSON-LD IRI value (term, compact IRI, IRI) to an absolute
* IRI and relabels blank nodes
*
* @param mixed $value The value to be expanded to an absolute IRI.
* @param array $activectx The active context.
* @param bool $relativeIri Specifies whether $value should be treated as
* relative IRI against the base IRI or not.
* @param bool $vocabRelative Specifies whether $value is relative to @vocab
* if set or not.
* @param null|JsonObject $localctx If the IRI is being expanded as part of context
* processing, the current local context has to be
* passed as well.
* @param array $path A path of already processed terms to detect
* circular dependencies
*
* @return string The expanded IRI.
*/
private function expandIri(
$value,
$activectx,
$relativeIri = false,
$vocabRelative = false,
$localctx = null,
$path = array()
) {
if ((null === $value) || in_array($value, self::$keywords)) {
return $value;
}
if ($localctx) {
if (in_array($value, $path)) {
throw new JsonLdException(
JsonLdException::CYCLIC_IRI_MAPPING,
'Cycle in context definition detected: ' . join(' -> ', $path) . ' -> ' . $path[0],
$localctx
);
} else {
$path[] = $value;
if (count($path) >= self::CONTEXT_MAX_IRI_RECURSIONS) {
throw new JsonLdException(
JsonLdException::UNSPECIFIED,
'Too many recursions in term definition: ' . join(' -> ', $path) . ' -> ' . $path[0],
$localctx
);
}
}
if (isset($localctx->{$value})) {
$nested = null;
if (is_string($localctx->{$value})) {
$nested = $localctx->{$value};
} elseif (isset($localctx->{$value}->{'@id'})) {
$nested = $localctx->{$value}->{'@id'};
}
if ($nested && (end($path) !== $nested)) {
return $this->expandIri($nested, $activectx, false, true, $localctx, $path);
}
}
}
// Terms apply only for vocab-relative IRIs
if ((true === $vocabRelative) && array_key_exists($value, $activectx)) {
return $activectx[$value]['@id'];
}
if (false !== strpos($value, ':')) {
list($prefix, $suffix) = explode(':', $value, 2);
if (('_' === $prefix) || ('//' === substr($suffix, 0, 2))) {
// Safety measure to prevent reassigned of, e.g., http://
// the "_" prefix is reserved for blank nodes and can't be expanded
return $value;
}
if ($localctx) {
$prefix = $this->expandIri($prefix, $activectx, false, true, $localctx, $path);
// If prefix contains a colon, we have successfully expanded it
if (false !== strpos($prefix, ':')) {
return $prefix . $suffix;
}
} elseif (array_key_exists($prefix, $activectx)) {
// compact IRI
return $activectx[$prefix]['@id'] . $suffix;
}
} else {
if ($vocabRelative && array_key_exists('@vocab', $activectx)) {
return $activectx['@vocab'] . $value;
} elseif (($relativeIri) && (null !== $activectx['@base'])) {
return (string) $activectx['@base']->resolve($value);
}
}
// can't expand it, return as is
return $value;
}
/**
* Compacts a JSON-LD document
*
* Attention: This method must be called with an expanded element,
* otherwise it might not work.
*
* @param mixed $element A JSON-LD element to be compacted.
* @param array $activectx The active context.
* @param array $inversectx The inverse context.
* @param null|string $activeprty The active property.
*
* @return mixed The compacted JSON-LD document.
*/
public function compact(&$element, $activectx = array(), $inversectx = array(), $activeprty = null)
{
if (is_array($element)) {
$result = array();
foreach ($element as &$item) {
$this->compact($item, $activectx, $inversectx, $activeprty);
if (null !== $item) {
$result[] = $item;
}
}
if ($this->compactArrays && (1 === count($result))) {
$element = $result[0];
} else {
$element = $result;
}
return;
}
if (false === is_object($element)) {
// element is already in compact form, nothing else to do
return;
}
if (property_exists($element, '@value') || property_exists($element, '@id')) {
$def = $this->getPropertyDefinition($activectx, $activeprty);
$element = $this->compactValue($element, $def, $activectx, $inversectx);
if (false === is_object($element)) {
return;
}
}
// Otherwise, compact all properties
$properties = get_object_vars($element);
ksort($properties);
$inReverse = ('@reverse' === $activeprty);
$element = new JsonObject();
foreach ($properties as $property => $value) {
if (in_array($property, self::$keywords)) {
if ('@id' === $property) {
$value = $this->compactIri($value, $activectx, $inversectx);
} elseif ('@type' === $property) {
if (is_string($value)) {
$value = $this->compactIri($value, $activectx, $inversectx, null, true);
} else {
foreach ($value as &$iri) {
$iri = $this->compactIri($iri, $activectx, $inversectx, null, true);
}
if ($this->compactArrays && (1 === count($value))) {
$value = $value[0];
}
}
} elseif (('@graph' === $property) || ('@list' === $property)) {
$this->compact($value, $activectx, $inversectx, $property);
if (false === is_array($value)) {
$value = array($value);
}
} elseif ('@reverse' === $property) {
$this->compact($value, $activectx, $inversectx, $property);
// Move reverse properties out of the map into element
foreach (get_object_vars($value) as $prop => $val) {
if ($this->getPropertyDefinition($activectx, $prop, '@reverse')) {
$alwaysArray = ('@set' === $this->getPropertyDefinition($activectx, $prop, '@container'));
self::mergeIntoProperty($element, $prop, $val, $alwaysArray);
unset($value->{$prop});
}
}
if (0 === count(get_object_vars($value))) {