forked from easyrdf/easyrdf
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathGraph.php
1768 lines (1593 loc) · 59.3 KB
/
Graph.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
namespace EasyRdf;
use EasyRdf\Http\Client;
/**
* EasyRdf
*
* LICENSE
*
* Copyright (c) 2009-2020 Nicholas J Humfrey. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author 'Nicholas J Humfrey" may be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright Copyright (c) 2009-2020 Nicholas J Humfrey
* @license https://www.opensource.org/licenses/bsd-license.php
*/
/**
* Container for collection of EasyRdf\Resource objects.
*
* @copyright Copyright (c) 2009-2020 Nicholas J Humfrey
* @license https://www.opensource.org/licenses/bsd-license.php
*
* PHPStan related:
*
* @property string $test
*
* @see https://phpstan.org/writing-php-code/phpdocs-basics#magic-properties
*/
class Graph
{
/** The URI of the graph */
private $uri;
private $parsedUri;
/** Array of resources contained in the graph */
private $resources = [];
private $index = [];
private $revIndex = [];
/** Counter for the number of bnodes */
private $bNodeCount = 0;
/** Array of URLs that have been loaded into the graph */
private $loaded = [];
private $maxRedirects = 10;
/**
* Constructor
*
* If no URI is given then an unnamed graph is created.
*
* The $data parameter is optional and will be parsed into
* the graph if given.
*
* The data format is optional and should be specified if it
* can't be guessed by EasyRdf.
*
* @param string $uri The URI of the graph
* @param string $data Data for the graph
* @param string $format The document type of the data (e.g. rdfxml)
*
* @return Graph
*/
public function __construct($uri = null, $data = null, $format = null)
{
$this->checkResourceParam($uri, true);
if ($uri) {
$this->uri = $uri;
$this->parsedUri = new ParsedUri($uri);
if ($data) {
$this->parse($data, $format, $this->uri);
}
}
}
/**
* Create a new graph and load RDF data from a URI into it
*
* This static function is shorthand for:
* $graph = new \EasyRdf\Graph($uri);
* $graph->load($uri, $format);
*
* The document format is optional but should be specified if it
* can't be guessed or got from the HTTP headers.
*
* If the document format is given, then the HTTP Accept header is
* set to the MIME type of the requested format.
*
* @param string $uri The URI of the data to load
* @param string|null $format Optional format of the data (eg. rdfxml or text/turtle)
*
* @return Graph The new the graph object
*/
public static function newAndLoad($uri, $format = null)
{
$graph = new self($uri);
$graph->load($uri, $format);
return $graph;
}
/** Get or create a resource stored in a graph
*
* If the resource did not previously exist, then a new resource will
* be created. If you provide an RDF type and that type is registered
* with the EasyRdf\TypeMapper, then the resource will be an instance
* of the class registered.
*
* If URI is null, then the URI of the graph is used.
*
* @param string $uri The URI of the resource
* @param mixed $types RDF type of a new resource (e.g. foaf:Person)
*
* @return \EasyRdf\Resource
*
* @throws \InvalidArgumentException
*/
public function resource($uri = null, $types = [])
{
$this->checkResourceParam($uri, true);
if (!$uri) {
throw new \InvalidArgumentException('$uri is null and EasyRdf\Graph object has no URI either.');
}
// Resolve relative URIs
if ($this->parsedUri) {
$uri = $this->parsedUri->resolve($uri)->toString();
}
// Add the types
$this->addType($uri, $types);
// Create resource object if it doesn't already exist
if (!isset($this->resources[$uri])) {
$resClass = $this->classForResource($uri);
$this->resources[$uri] = new $resClass($uri, $this);
}
return $this->resources[$uri];
}
/** Work out the class to instantiate a resource as
* @ignore
*/
protected function classForResource($uri)
{
$rdfType = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
if (isset($this->index[$uri][$rdfType])) {
foreach ($this->index[$uri][$rdfType] as $type) {
if ('uri' == $type['type'] || 'bnode' == $type['type']) {
$class = TypeMapper::get($type['value']);
if (null != $class) {
return $class;
}
}
}
}
// Parsers don't typically add a rdf:type to rdf:List, so we have to
// do a bit of 'inference' here using properties.
if ('http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' == $uri
|| isset($this->index[$uri]['http://www.w3.org/1999/02/22-rdf-syntax-ns#first'])
|| isset($this->index[$uri]['http://www.w3.org/1999/02/22-rdf-syntax-ns#rest'])
) {
return 'EasyRdf\Collection';
}
return TypeMapper::getDefaultResourceClass();
}
/**
* Create a new blank node in the graph and return it.
*
* If you provide an RDF type and that type is registered
* with the EasyRdf\TypeMapper, then the resource will be an instance
* of the class registered.
*
* @param mixed $types RDF type of a new blank node (e.g. foaf:Person)
*
* @return \EasyRdf\Resource The new blank node
*/
public function newBNode($types = [])
{
return $this->resource($this->newBNodeId(), $types);
}
/**
* Create a new unique blank node identifier and return it.
*
* @return string The new blank node identifier (e.g. _:genid1)
*/
public function newBNodeId()
{
return '_:genid'.(++$this->bNodeCount);
}
/**
* Parse some RDF data into the graph object.
*
* @param string $data Data to parse for the graph
* @param string $format Optional format of the data
* @param string $uri The URI of the data to load
*
* @return int The number of triples added to the graph
*
* @throws Exception
*/
public function parse($data, $format = null, $uri = null)
{
$this->checkResourceParam($uri, true);
if (empty($format) || 'guess' == $format) {
// Guess the format if it is Unknown
$format = Format::guessFormat($data, $uri);
} else {
$format = Format::getFormat($format);
}
if (!$format) {
throw new Exception('Unable to parse data of an unknown format.');
}
$parser = $format->newParser();
return $parser->parse($this, $data, $format, $uri);
}
/**
* Parse a file containing RDF data into the graph object.
*
* @param string $filename The path of the file to load
* @param string $format Optional format of the file
* @param string $uri The URI of the file to load
*
* @return int The number of triples added to the graph
*/
public function parseFile($filename, $format = null, $uri = null)
{
if (null === $uri) {
$uri = "file://$filename";
}
return $this->parse(
file_get_contents($filename),
$format,
$uri
);
}
/**
* Load RDF data into the graph from a URI.
*
* If no URI is given, then the URI of the graph will be used.
*
* The document format is optional but should be specified if it
* can't be guessed or got from the HTTP headers.
*
* If the document format is given, then the HTTP Accept header is
* set to the MIME type of the requested format.
*
* @param string $uri The URI of the data to load
* @param string $format Optional format of the data (eg. rdfxml or text/turtle)
*
* @return int The number of triples added to the graph
*
* @throws Exception
* @throws Http\Exception
*/
public function load($uri = null, $format = null)
{
$this->checkResourceParam($uri, true);
if (!$uri) {
throw new Exception('No URI given to load() and the graph does not have a URI.');
}
// Setup the HTTP client
$client = Http::getDefaultHttpClient();
$client->resetParameters(true);
$client->setConfig(['maxredirects' => 0]);
$client->setMethod('GET');
if ($format && 'guess' !== $format) {
if (str_contains($format, '/')) {
if ($client instanceof Client) {
$client->setHeaders('Accept', $format);
} else {
$client->setHeaders(['Accept' => $format]);
}
} else {
$formatObj = Format::getFormat($format);
if ($client instanceof Client) {
$client->setHeaders('Accept', $formatObj->getDefaultMimeType());
} else {
$client->setHeaders(['Accept' => $formatObj->getDefaultMimeType()]);
}
}
} else {
$acceptHeader = Format::formatAcceptHeader([
'application/ld+json' => 1.0,
'application/rdf+xml' => 0.9,
'text/turtle' => 0.8,
'application/n-quads' => 0.7,
'application/n-triples' => 0.7,
]);
// Send a list of all the formats we can parse
if ($client instanceof Client) {
$client->setHeaders('Accept', $acceptHeader);
} else {
$client->setHeaders(['Accept' => $acceptHeader]);
}
}
$requestUrl = $uri;
$response = null;
$redirectCounter = 0;
do {
// Have we already loaded it into the graph?
$requestUrl = Utils::removeFragmentFromUri($requestUrl);
if (\in_array($requestUrl, $this->loaded)) {
return 0;
}
// Make the HTTP request
if ($client instanceof Client) {
$client->setHeaders('host', null);
} else {
$client->setHeaders(['host' => null]);
}
$client->setUri($requestUrl);
$response = $client->request();
// Add the URL to the list of URLs loaded
$this->loaded[] = $requestUrl;
if ($response->isRedirect() && $location = $response->getHeader('location')) {
// Avoid problems with buggy servers that add whitespace
$location = trim($location);
// Some servers return relative URLs in the location header
// resolve it in relation to previous request
$baseUri = new ParsedUri($requestUrl);
$requestUrl = $baseUri->resolve($location)->toString();
$requestUrl = Utils::removeFragmentFromUri($requestUrl);
// If it is a 303 then drop the parameters
if (303 == $response->getStatus()) {
$client->resetParameters();
}
++$redirectCounter;
} elseif ($response->isSuccessful()) {
// If we didn't get any location, stop redirecting
break;
} else {
throw new Http\Exception("HTTP request for {$requestUrl} failed: ".$response->getMessage(), $response->getStatus(), null, $response->getBody());
}
} while ($redirectCounter < $this->maxRedirects);
if (!$format || 'guess' == $format) {
list($format) = Utils::parseMimeType(
$response->getHeader('Content-Type')
);
}
// Parse the data
return $this->parse($response->getBody(), $format, $uri);
}
/** Get an associative array of all the resources stored in the graph.
* The keys of the array is the URI of the EasyRdf\Resource.
*
* @return \EasyRdf\Resource[]
*/
public function resources()
{
foreach ($this->index as $subject => $properties) {
if (!isset($this->resources[$subject])) {
$this->resource($subject);
}
}
foreach ($this->revIndex as $object => $properties) {
if (!isset($this->resources[$object])) {
$this->resource($object);
}
}
return $this->resources;
}
/** Get an arry of resources matching a certain property and optional value.
*
* For example this routine could be used as a way of getting
* everyone who has name:
* $people = $graph->resourcesMatching('foaf:name')
*
* Or everyone who is male:
* $people = $graph->resourcesMatching('foaf:gender', 'male');
*
* Or all homepages:
* $people = $graph->resourcesMatching('^foaf:homepage');
*
* @param string $property the property to check
* @param mixed $value optional, the value of the propery to check for
*
* @return \EasyRdf\Resource[]
*/
public function resourcesMatching($property, $value = null)
{
$this->checkSinglePropertyParam($property, $inverse);
$this->checkValueParam($value);
// Use the reverse index if it is an inverse property
if ($inverse) {
$index = &$this->revIndex;
} else {
$index = &$this->index;
}
$matched = [];
foreach ($index as $subject => $props) {
if (isset($index[$subject][$property])) {
if (isset($value)) {
foreach ($this->index[$subject][$property] as $v) {
if ($v['type'] == $value['type']
&& $v['value'] == $value['value']) {
$matched[] = $this->resource($subject);
break;
}
}
} else {
$matched[] = $this->resource($subject);
}
}
}
return $matched;
}
/** Get the URI of the graph
*
* @return string|null The URI of the graph
*/
public function getUri()
{
return $this->uri;
}
/** Check that a URI/resource parameter is valid, and convert it to a string
* @ignore
*/
protected function checkResourceParam(&$resource, $allowNull = false)
{
if (true == $allowNull) {
if (null === $resource) {
if ($this->uri) {
$resource = $this->uri;
} else {
return;
}
}
} elseif (null === $resource) {
throw new \InvalidArgumentException('$resource should be either IRI, blank-node identifier or EasyRdf\Resource. got null');
}
if (\is_object($resource) && $resource instanceof Resource) {
$resource = $resource->getUri();
} elseif (\is_object($resource) && $resource instanceof ParsedUri) {
$resource = (string) $resource;
} elseif (\is_string($resource)) {
if ('' == $resource) {
throw new \InvalidArgumentException('$resource should be either IRI, blank-node identifier or EasyRdf\Resource. got empty string');
} elseif (preg_match('|^<(.+)>$|', $resource, $matches)) {
$resource = $matches[1];
} else {
$resource = RdfNamespace::expand($resource);
}
} else {
throw new \InvalidArgumentException('$resource should be either IRI, blank-node identifier or EasyRdf\Resource');
}
}
/** Check that a single URI/property parameter (not a property path)
* is valid, and expand it if required
*
* @ignore
*/
protected function checkSinglePropertyParam(&$property, &$inverse)
{
if (\is_object($property) && $property instanceof Resource) {
$property = $property->getUri();
} elseif (\is_object($property) && $property instanceof ParsedUri) {
$property = (string) $property;
} elseif (\is_string($property)) {
if ('' == $property) {
throw new \InvalidArgumentException('$property cannot be an empty string');
} elseif ('^' == substr($property, 0, 1)) {
$inverse = true;
$property = RdfNamespace::expand(substr($property, 1));
} elseif ('_:' == substr($property, 0, 2)) {
throw new \InvalidArgumentException('$property cannot be a blank node');
} else {
$inverse = false;
$property = RdfNamespace::expand($property);
}
}
if (null === $property || !\is_string($property)) {
throw new \InvalidArgumentException('$property should be a string or EasyRdf\Resource and cannot be null');
}
}
/** Check that a value parameter is valid, and convert it to an associative array if needed
* @ignore
*/
protected function checkValueParam(&$value)
{
if (isset($value)) {
if (\is_object($value)) {
if (!method_exists($value, 'toRdfPhp')) {
// Convert to a literal object
$value = Literal::create($value);
}
$value = $value->toRdfPhp();
} elseif (\is_array($value)) {
if (!isset($value['type'])) {
throw new \InvalidArgumentException("\$value is missing a 'type' key");
}
if (!isset($value['value'])) {
throw new \InvalidArgumentException("\$value is missing a 'value' key");
}
// Fix ordering and remove unknown keys
$value = [
'type' => (string) $value['type'],
'value' => (string) $value['value'],
'lang' => isset($value['lang']) ? (string) ($value['lang']) : null,
'datatype' => isset($value['datatype']) ? (string) ($value['datatype']) : null,
];
} else {
$value = [
'type' => 'literal',
'value' => (string) $value,
'datatype' => Literal::getDatatypeForValue($value),
];
}
if (!\in_array($value['type'], ['uri', 'bnode', 'literal'], true)) {
throw new \InvalidArgumentException('$value does not have a valid type ('.$value['type'].')');
}
if (empty($value['datatype'])) {
unset($value['datatype']);
}
if (empty($value['lang'])) {
unset($value['lang']);
}
if (isset($value['lang']) && isset($value['datatype'])) {
throw new \InvalidArgumentException('$value cannot have both and language and a datatype');
}
}
}
/** Get a single value for a property of a resource
*
* If multiple values are set for a property then the value returned
* may be arbitrary.
*
* If $property is an array, then the first item in the array that matches
* a property that exists is returned.
*
* This method will return null if the property does not exist.
*
* @param string $resource The URI of the resource (e.g. http://example.com/joe#me)
* @param string|array|\EasyRdf\Resource|null $propertyPath A valid property path
* @param string $type The type of value to filter by (e.g. literal or resource)
* @param string $lang The language to filter by (e.g. en)
*
* @return mixed A value associated with the property
*
* @throws \InvalidArgumentException
*/
public function get($resource, $propertyPath, $type = null, $lang = null)
{
$this->checkResourceParam($resource);
if (\is_object($propertyPath) && $propertyPath instanceof Resource) {
return $this->getSingleProperty($resource, $propertyPath->getUri(), $type, $lang);
} elseif (\is_string($propertyPath) && preg_match('|^(\^?)<(.+)>|', $propertyPath, $matches)) {
return $this->getSingleProperty($resource, "$matches[1]$matches[2]", $type, $lang);
} elseif (\is_array($propertyPath)) {
$propertyPath = implode('|', $propertyPath); // convert to path expression
} elseif (null === $propertyPath || !\is_string($propertyPath)) {
throw new \InvalidArgumentException('$propertyPath should be a string, array or EasyRdf\Resource and cannot be null');
} elseif ('' === $propertyPath) {
throw new \InvalidArgumentException('$propertyPath cannot be an empty string');
}
// Loop through each component in the path
foreach (explode('/', $propertyPath) as $part) {
// Stop if we come to a literal
if ($resource instanceof Literal) {
return null;
}
// Try each of the alternative paths
foreach (explode('|', $part) as $p) {
$res = $this->getSingleProperty($resource, $p, $type, $lang);
if ($res) {
break;
}
}
// Stop if nothing was found
$resource = $res;
if (!$resource) {
break;
}
}
return $resource;
}
/** Get a single value for a property of a resource
*
* @param string $resource The URI of the resource (e.g. http://example.com/joe#me)
* @param string $property The name of the property (e.g. foaf:name)
* @param string $type The type of value to filter by (e.g. literal or resource)
* @param string $lang The language to filter by (e.g. en)
*
* @return mixed A value associated with the property
*
* @ignore
*/
protected function getSingleProperty($resource, $property, $type = null, $lang = null)
{
$this->checkResourceParam($resource);
$this->checkSinglePropertyParam($property, $inverse);
// Get an array of values for the property
$values = $this->propertyValuesArray($resource, $property, $inverse);
if (!isset($values)) {
return null;
}
// Filter the results
$result = null;
if ($type) {
foreach ($values as $value) {
if ('literal' == $type && 'literal' == $value['type']) {
if (null == $lang || (isset($value['lang']) && $value['lang'] == $lang)) {
$result = $value;
break;
}
} elseif ('resource' == $type) {
if ('uri' == $value['type'] || 'bnode' == $value['type']) {
$result = $value;
break;
}
}
}
} else {
$result = $values[0];
}
// Convert the internal data structure into a PHP object
return $this->arrayToObject($result);
}
/** Get a single literal value for a property of a resource
*
* If multiple values are set for a property then the value returned
* may be arbitrary.
*
* This method will return null if there is not literal value for the
* property.
*
* @param string $resource The URI of the resource (e.g. http://example.com/joe#me)
* @param string|array $property The name of the property (e.g. foaf:name)
* @param string $lang The language to filter by (e.g. en)
*
* @return Literal Literal value associated with the property
*/
public function getLiteral($resource, $property, $lang = null)
{
return $this->get($resource, $property, 'literal', $lang);
}
/** Get a single resource value for a property of a resource
*
* If multiple values are set for a property then the value returned
* may be arbitrary.
*
* This method will return null if there is not resource for the
* property.
*
* @param string $resource The URI of the resource (e.g. http://example.com/joe#me)
* @param string|array $property The name of the property (e.g. foaf:name)
*
* @return \EasyRdf\Resource Resource associated with the property
*/
public function getResource($resource, $property)
{
return $this->get($resource, $property, 'resource');
}
/** Return all the values for a particular property of a resource
* @ignore
*/
protected function propertyValuesArray($resource, $property, $inverse = false)
{
// Is an inverse property being requested?
if ($inverse) {
if (isset($this->revIndex[$resource])) {
$properties = &$this->revIndex[$resource];
}
} else {
if (isset($this->index[$resource])) {
$properties = &$this->index[$resource];
}
}
if (isset($properties[$property])) {
return $properties[$property];
} else {
return null;
}
}
/** Get an EasyRdf\Resource or EasyRdf\Literal object from an associative array.
* @ignore
*/
protected function arrayToObject($data)
{
if ($data) {
if ('uri' == $data['type'] || 'bnode' == $data['type']) {
return $this->resource($data['value']);
} else {
return Literal::create($data);
}
} else {
return null;
}
}
/** Get all values for a property path
*
* This method will return an empty array if the property does not exist.
*
* @param string $resource The URI of the resource (e.g. http://example.com/joe#me)
* @param string|\EasyRdf\Resource|null $propertyPath A valid property path
* @param string $type The type of value to filter by (e.g. literal)
* @param string $lang The language to filter by (e.g. en)
*
* @return array An array of values associated with the property
*
* @throws \InvalidArgumentException
*/
public function all($resource, $propertyPath, $type = null, $lang = null)
{
$this->checkResourceParam($resource);
if (\is_object($propertyPath) && $propertyPath instanceof Resource) {
return $this->allForSingleProperty($resource, $propertyPath->getUri(), $type, $lang);
} elseif (\is_string($propertyPath) && preg_match('|^(\^?)<(.+)>|', $propertyPath, $matches)) {
return $this->allForSingleProperty($resource, "$matches[1]$matches[2]", $type, $lang);
} elseif (null === $propertyPath || !\is_string($propertyPath)) {
throw new \InvalidArgumentException('$propertyPath should be a string or EasyRdf\Resource and cannot be null');
} elseif ('' === $propertyPath) {
throw new \InvalidArgumentException('$propertyPath cannot be an empty string');
}
$objects = [$resource];
// Loop through each component in the path
foreach (explode('/', $propertyPath) as $part) {
$results = [];
foreach (explode('|', $part) as $p) {
foreach ($objects as $o) {
// Ignore literals found earlier in path
if ($o instanceof Literal) {
continue;
}
$results = array_merge(
$results,
$this->allForSingleProperty($o, $p, $type, $lang)
);
}
}
// Stop if we don't have anything
if (empty($objects)) {
break;
}
// Use the results as the input to the next iteration
$objects = $results;
}
return $results;
}
/** Get all values for a single property of a resource
*
* @param string $resource The URI of the resource (e.g. http://example.com/joe#me)
* @param string $property The name of the property (e.g. foaf:name)
* @param string $type The type of value to filter by (e.g. literal)
* @param string $lang The language to filter by (e.g. en)
*
* @return array An array of values associated with the property
*
* @ignore
*/
protected function allForSingleProperty($resource, $property, $type = null, $lang = null)
{
$this->checkResourceParam($resource);
$this->checkSinglePropertyParam($property, $inverse);
// Get an array of values for the property
$values = $this->propertyValuesArray($resource, $property, $inverse);
if (!isset($values)) {
return [];
}
$objects = [];
if ($type) {
foreach ($values as $value) {
if ('literal' == $type && 'literal' == $value['type']) {
if (null == $lang || (isset($value['lang']) && $value['lang'] == $lang)) {
$objects[] = $this->arrayToObject($value);
}
} elseif ('resource' == $type) {
if ('uri' == $value['type'] || 'bnode' == $value['type']) {
$objects[] = $this->arrayToObject($value);
}
}
}
} else {
foreach ($values as $value) {
$objects[] = $this->arrayToObject($value);
}
}
return $objects;
}
/** Get all literal values for a property of a resource
*
* This method will return an empty array if the resource does not
* has any literal values for that property.
*
* @param string $resource The URI of the resource (e.g. http://example.com/joe#me)
* @param string $property The name of the property (e.g. foaf:name)
* @param string $lang The language to filter by (e.g. en)
*
* @return array An array of values associated with the property
*/
public function allLiterals($resource, $property, $lang = null)
{
return $this->all($resource, $property, 'literal', $lang);
}
/** Get all resources for a property of a resource
*
* This method will return an empty array if the resource does not
* has any resources for that property.
*
* @param string $resource The URI of the resource (e.g. http://example.com/joe#me)
* @param string $property The name of the property (e.g. foaf:name)
*
* @return array An array of values associated with the property
*/
public function allResources($resource, $property)
{
return $this->all($resource, $property, 'resource');
}
/** Get all the resources in the graph of a certain type
*
* If no resources of the type are available and empty
* array is returned.
*
* @param string $type The type of the resource (e.g. foaf:Person)
*
* @return array The array of resources
*/
public function allOfType($type)
{
return $this->all($type, '^rdf:type');
}
/** Count the number of values for a property of a resource
*
* @param string $resource The URI of the resource (e.g. http://example.com/joe#me)
* @param string $property The name of the property (e.g. foaf:name)
* @param string $type The type of value to filter by (e.g. literal)
* @param string $lang The language to filter by (e.g. en)
*
* @return int The number of values for this property
*/
public function countValues($resource, $property, $type = null, $lang = null)
{
return \count($this->all($resource, $property, $type, $lang));
}
/** Concatenate all values for a property of a resource into a string.
*
* The default is to join the values together with a space character.
* This method will return an empty string if the property does not exist.
*
* @param mixed $resource The resource to get the property on
* @param string $property The name of the property (e.g. foaf:name)
* @param string $glue the string to glue the values together with
* @param string $lang The language to filter by (e.g. en)
*
* @return string concatenation of all the values
*/
public function join($resource, $property, $glue = ' ', $lang = null)
{
return implode($glue, $this->all($resource, $property, 'literal', $lang));
}
/** Add data to the graph
*
* The resource can either be a resource or the URI of a resource.
*
* Example:
* $graph->add("http://www.example.com", 'dc:title', 'Title of Page');
*
* @param mixed $resource The resource to add data to
* @param mixed $property The property name
* @param mixed $value The new value for the property
*
* @return int The number of values added (1 or 0)
*/
public function add($resource, $property, $value)
{
$this->checkResourceParam($resource);
$this->checkSinglePropertyParam($property, $inverse);
$this->checkValueParam($value);
// No value given?
if (null === $value) {
return 0;
}
// Check that the value doesn't already exist
if (isset($this->index[$resource][$property])) {
foreach ($this->index[$resource][$property] as $v) {
if ($v == $value) {
return 0;
}
}
}
$this->index[$resource][$property][] = $value;
// Add to the reverse index if it is a resource
if ('uri' == $value['type'] || 'bnode' == $value['type']) {
$uri = $value['value'];
$this->revIndex[$uri][$property][] = [
'type' => '_:' == substr($resource, 0, 2) ? 'bnode' : 'uri',
'value' => $resource,
];
}
// Success
return 1;
}
/** Add a literal value as a property of a resource
*