summaryrefslogtreecommitdiffstats
path: root/core/vendor/easyrdf/easyrdf/lib/EasyRdf/Graph.php
blob: 5bb3ab123fb10b024c99756db3c54de9e6facc3c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
<?php

/**
 * EasyRdf
 *
 * LICENSE
 *
 * Copyright (c) 2009-2012 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.
 *
 * @package    EasyRdf
 * @copyright  Copyright (c) 2009-2012 Nicholas J Humfrey
 * @license    http://www.opensource.org/licenses/bsd-license.php
 * @version    $Id$
 */

/**
 * Container for collection of EasyRdf_Resources.
 *
 * @package    EasyRdf
 * @copyright  Copyright (c) 2009-2012 Nicholas J Humfrey
 * @license    http://www.opensource.org/licenses/bsd-license.php
 */
class EasyRdf_Graph
{
    /** The URI of the graph */
    private $uri = null;
    private $parsedUri = null;

    /** Array of resources contained in the graph */
    private $resources = array();

    private $index = array();
    private $revIndex = array();

    /** Counter for the number of bnodes */
    private $bNodeCount = 0;

    /** Array of URLs that have been loaded into the graph */
    private $loaded = array();

    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 object EasyRdf_Graph
     */
    public function __construct($uri = null, $data = null, $format = null)
    {
        $this->checkResourceParam($uri, true);

        if ($uri) {
            $this->uri = $uri;
            $this->parsedUri = new EasyRdf_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 type is optional but should be specified if it
     * can't be guessed or got from the HTTP headers.
     *
     * @param  string  $uri     The URI of the data to load
     * @param  string  $format  Optional format of the data (eg. rdfxml)
     * @return object EasyRdf_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 object EasyRdf_Resource
     */
    public function resource($uri = null, $types = array())
    {
        $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)
    {
        $resClass = 'EasyRdf_Resource';
        $rdfType = EasyRdf_Namespace::expand('rdf:type');
        if (isset($this->index[$uri][$rdfType])) {
            foreach ($this->index[$uri][$rdfType] as $type) {
                if ($type['type'] == 'uri' or $type['type'] == 'bnode') {
                    $class = EasyRdf_TypeMapper::get($type['value']);
                    if ($class != null) {
                        $resClass = $class;
                        break;
                    }
                }

            }
        }
        return $resClass;
    }

    /**
     * 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 object EasyRdf_Resource The new blank node
     */
    public function newBNode($types = array())
    {
        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 integer          The number of triples added to the graph
     */
    public function parse($data, $format = null, $uri = null)
    {
        $this->checkResourceParam($uri, true);

        if (empty($format) or $format == 'guess') {
            // Guess the format if it is Unknown
            $format = EasyRdf_Format::guessFormat($data, $uri);
        } else {
            $format = EasyRdf_Format::getFormat($format);
        }

        if (!$format) {
            throw new EasyRdf_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 integer           The number of triples added to the graph
     */
    public function parseFile($filename, $format = null, $uri = null)
    {
        if ($uri === null) {
            $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 type is optional but should be specified if it
     * can't be guessed or got from the HTTP headers.
     *
     * @param  string  $uri     The URI of the data to load
     * @param  string  $format  Optional format of the data (eg. rdfxml)
     * @return integer          The number of triples added to the graph
     */
    public function load($uri = null, $format = null)
    {
        $this->checkResourceParam($uri, true);

        if (!$uri) {
            throw new EasyRdf_Exception(
                "No URI given to load() and the graph does not have a URI."
            );
        }

        // Setup the HTTP client
        $client = EasyRdf_Http::getDefaultHttpClient();
        $client->resetParameters(true);
        $client->setConfig(array('maxredirects' => 0));
        $client->setMethod('GET');
        $client->setHeaders('Accept', EasyRdf_Format::getHttpAcceptHeader());

        $requestUrl = $uri;
        $response = null;
        $redirectCounter = 0;
        do {
            // Have we already loaded it into the graph?
            $requestUrl = EasyRdf_Utils::removeFragmentFromUri($requestUrl);
            if (in_array($requestUrl, $this->loaded)) {
                return 0;
            }

            // Make the HTTP request
            $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() and $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 EasyRdf_ParsedUri($requestUrl);
                $requestUrl = $baseUri->resolve($location)->toString();
                $requestUrl = EasyRdf_Utils::removeFragmentFromUri($requestUrl);

                // If it is a 303 then drop the parameters
                if ($response->getStatus() == 303) {
                    $client->resetParameters();
                }

                ++$redirectCounter;
            } elseif ($response->isSuccessful()) {
                // If we didn't get any location, stop redirecting
                break;
            } else {
                throw new EasyRdf_Exception(
                    "HTTP request for $requestUrl failed: ".$response->getMessage()
                );
            }
        } while ($redirectCounter < $this->maxRedirects);

        if (!$format or $format == 'guess') {
            list($format, $params) = EasyRdf_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 array Array of EasyRdf_Resource
     */
    public function resources()
    {
        foreach ($this->index as $subject => $properties) {
            $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 array   Array of 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 = array();
        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'] and
                            $v['value'] == $value['value']) {
                            $matched[] = $this->resource($subject);
                            break;
                        }
                    }
                } else {
                    $matched[] = $this->resource($subject);
                }
            }
        }
        return $matched;
    }

    /** Get the URI of the graph
     *
     * @return string 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 ($allowNull == true) {
            if ($resource === null) {
                if ($this->uri) {
                    $resource = $this->uri;
                } else {
                    return;
                }
            }
        } elseif ($resource === null) {
            throw new InvalidArgumentException(
                "\$resource cannot be null"
            );
        }

        if (is_object($resource) and $resource instanceof EasyRdf_Resource) {
            $resource = $resource->getUri();
        } elseif (is_object($resource) and $resource instanceof EasyRdf_ParsedUri) {
            $resource = strval($resource);
        } elseif (is_string($resource)) {
            if ($resource == '') {
                throw new InvalidArgumentException(
                    "\$resource cannot be an empty string"
                );
            } elseif (preg_match("|^<(.+)>$|", $resource, $matches)) {
                $resource = $matches[1];
            } else {
                $resource = EasyRdf_Namespace::expand($resource);
            }
        } else {
            throw new InvalidArgumentException(
                "\$resource should be a string or an 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) and $property instanceof EasyRdf_Resource) {
            $property = $property->getUri();
        } elseif (is_object($property) and $property instanceof EasyRdf_ParsedUri) {
            $property = strval($property);
        } elseif (is_string($property)) {
            if ($property == '') {
                throw new InvalidArgumentException(
                    "\$property cannot be an empty string"
                );
            } elseif (substr($property, 0, 1) == '^') {
                $inverse = true;
                $property = EasyRdf_Namespace::expand(substr($property, 1));
            } elseif (substr($property, 0, 2) == '_:') {
                throw new InvalidArgumentException(
                    "\$property cannot be a blank node"
                );
            } else {
                $inverse = false;
                $property = EasyRdf_Namespace::expand($property);
            }
        }

        if ($property === null or !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, 'toArray')) {
                    $value = $value->toArray();
                } else {
                    throw new InvalidArgumentException(
                        "\$value should respond to the method toArray()"
                    );
                }
            } 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 = array(
                    'type' => strval($value['type']),
                    'value' => strval($value['value']),
                    'lang' => isset($value['lang']) ? strval($value['lang']) : null,
                    'datatype' => isset($value['datatype']) ? strval($value['datatype']) : null
                );
            } else {
                $value = array(
                    'type' => 'literal',
                    'value' => strval($value),
                    'datatype' => EasyRdf_Literal::getDatatypeForValue($value)
                );
            }
            if (!in_array($value['type'], array('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']) and 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    $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
     */
    public function get($resource, $propertyPath, $type = null, $lang = null)
    {
        $this->checkResourceParam($resource);

        if (is_object($propertyPath) and $propertyPath instanceof EasyRdf_Resource) {
            return $this->getSingleProperty($resource, $propertyPath->getUri(), $type, $lang);
        } elseif (is_string($propertyPath) and preg_match('|^(\^?)<(.+)>|', $propertyPath, $matches)) {
            return $this->getSingleProperty($resource, "$matches[1]$matches[2]", $type, $lang);
        } elseif ($propertyPath === null or !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"
            );
        }

        // Loop through each component in the path
        foreach (explode('/', $propertyPath) as $part) {
            // Stop if we come to a literal
            if ($resource instanceof EasyRdf_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 ($type == 'literal' and $value['type'] == 'literal') {
                    if ($lang == null or (isset($value['lang']) and $value['lang'] == $lang)) {
                        $result = $value;
                        break;
                    }
                } elseif ($type == 'resource') {
                    if ($value['type'] == 'uri' or $value['type'] == 'bnode') {
                        $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 object EasyRdf_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 object 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 ($data['type'] == 'uri' or $data['type'] == 'bnode') {
                return $this->resource($data['value']);
            } else {
                return EasyRdf_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  $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
     */
    public function all($resource, $propertyPath, $type = null, $lang = null)
    {
        $this->checkResourceParam($resource);

        if (is_object($propertyPath) and $propertyPath instanceof EasyRdf_Resource) {
            return $this->allForSingleProperty($resource, $propertyPath->getUri(), $type, $lang);
        } elseif (is_string($propertyPath) and preg_match('|^(\^?)<(.+)>|', $propertyPath, $matches)) {
            return $this->allForSingleProperty($resource, "$matches[1]$matches[2]", $type, $lang);
        } elseif ($propertyPath === null or !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 = array($resource);

        // Loop through each component in the path
        foreach (explode('/', $propertyPath) as $part) {

            $results = array();
            foreach (explode('|', $part) as $p) {
                foreach ($objects as $o) {
                    // Ignore literals found earlier in path
                    if ($o instanceof EasyRdf_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 $objects;
    }

    /** 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 array();
        }

        $objects = array();
        if ($type) {
            foreach ($values as $value) {
                if ($type == 'literal' and $value['type'] == 'literal') {
                    if ($lang == null or (isset($value['lang']) and $value['lang'] == $lang)) {
                        $objects[] = $this->arrayToObject($value);
                    }
                } elseif ($type == 'resource') {
                    if ($value['type'] == 'uri' or $value['type'] == 'bnode') {
                        $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 all 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 integer           The number of values for this property
     */
    public function count($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 join($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 integer           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 ($value === null) {
            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 ($value['type'] == 'uri' or $value['type'] == 'bnode') {
            $uri = $value['value'];
            $this->revIndex[$uri][$property][] = array(
                'type' => substr($resource, 0, 2) == '_:' ? 'bnode' : 'uri',
                'value' => $resource
            );
        }

        // Success
        return 1;
    }

    /** Add a literal value as a property of a resource
     *
     * The resource can either be a resource or the URI of a resource.
     * The value can either be a single value or an array of values.
     *
     * 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 value or values for the property
     * @param  string $lang      The language of the literal
     * @return integer           The number of values added
     */
    public function addLiteral($resource, $property, $value, $lang = null)
    {
        $this->checkResourceParam($resource);
        $this->checkSinglePropertyParam($property, $inverse);

        if (is_array($value)) {
            $added = 0;
            foreach ($value as $v) {
                $added += $this->addLiteral($resource, $property, $v, $lang);
            }
            return $added;
        } else {
            if ($lang) {
                $value = array(
                    'type' => 'literal',
                    'value' => $value,
                    'lang' => $lang
                );
            } else {
                $value = array(
                    'type' => 'literal',
                    'value' => $value,
                    'datatype' => EasyRdf_Literal::getDatatypeForValue($value)
                );
                if (empty($value['datatype'])) {
                    unset($value['datatype']);
                }
            }
            return $this->add($resource, $property, $value);
        }
    }

    /** Add a resource as a property of another resource
     *
     * The resource can either be a resource or the URI of a resource.
     *
     * Example:
     *   $graph->add("http://example.com/bob", 'foaf:knows', 'http://example.com/alice');
     *
     * @param  mixed $resource   The resource to add data to
     * @param  mixed $property   The property name
     * @param  mixed $resource2  The resource to be value of the property
     * @return integer           The number of values added
     */
    public function addResource($resource, $property, $resource2)
    {
        $this->checkResourceParam($resource);
        $this->checkSinglePropertyParam($property, $inverse);
        $this->checkResourceParam($resource2);

        return $this->add(
            $resource,
            $property,
            array(
                'type' => substr($resource2, 0, 2) == '_:' ? 'bnode' : 'uri',
                'value' => $resource2
            )
        );
    }

    /** Set a value for a property
     *
     * The new value will replace the existing values for the property.
     *
     * @param  string  $resource The resource to set the property on
     * @param  string  $property The name of the property (e.g. foaf:name)
     * @param  mixed   $value    The value for the property
     * @return integer           The number of values added (1 or 0)
     */
    public function set($resource, $property, $value)
    {
        $this->checkResourceParam($resource);
        $this->checkSinglePropertyParam($property, $inverse);
        $this->checkValueParam($value);

        // Delete the old values
        $this->delete($resource, $property);

        // Add the new values
        return $this->add($resource, $property, $value);
    }

    /** Delete a property (or optionally just a specific value)
     *
     * @param  mixed   $resource The resource to delete the property from
     * @param  string  $property The name of the property (e.g. foaf:name)
     * @param  mixed   $value The value to delete (null to delete all values)
     * @return integer The number of values deleted
     */
    public function delete($resource, $property, $value = null)
    {
        $this->checkResourceParam($resource);
        $this->checkSinglePropertyParam($property, $inverse);
        $this->checkValueParam($value);

        $count = 0;
        $property = EasyRdf_Namespace::expand($property);
        if (isset($this->index[$resource][$property])) {
            foreach ($this->index[$resource][$property] as $k => $v) {
                if (!$value or $v == $value) {
                    unset($this->index[$resource][$property][$k]);
                    $count++;
                    if ($v['type'] == 'uri' or $v['type'] == 'bnode') {
                        $this->deleteInverse($v['value'], $property, $resource);
                    }
                }
            }

            // Clean up the indexes - remove empty properties and resources
            if ($count) {
                if (count($this->index[$resource][$property]) == 0) {
                    unset($this->index[$resource][$property]);
                }
                if (count($this->index[$resource]) == 0) {
                    unset($this->index[$resource]);
                }
            }
        }

        return $count;
    }

    /** Delete a resource from a property of another resource
     *
     * The resource can either be a resource or the URI of a resource.
     *
     * Example:
     *   $graph->delete("http://example.com/bob", 'foaf:knows', 'http://example.com/alice');
     *
     * @param  mixed $resource   The resource to delete data from
     * @param  mixed $property   The property name
     * @param  mixed $resource2  The resource value of the property to be deleted
     */
    public function deleteResource($resource, $property, $resource2)
    {
        $this->checkResourceParam($resource);
        $this->checkSinglePropertyParam($property, $inverse);
        $this->checkResourceParam($resource2);

        return $this->delete(
            $resource,
            $property,
            array(
                'type' => substr($resource2, 0, 2) == '_:' ? 'bnode' : 'uri',
                'value' => $resource2
            )
        );
    }

    /** Delete a literal value from a property of a resource
     *
     * Example:
     *   $graph->delete("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 value of the property
     * @param  string $lang      The language of the literal
     */
    public function deleteLiteral($resource, $property, $value, $lang = null)
    {
        $this->checkResourceParam($resource);
        $this->checkSinglePropertyParam($property, $inverse);
        $this->checkValueParam($value);

        if ($lang) {
            $value['lang'] = $lang;
        }

        return $this->delete($resource, $property, $value);
    }

    /** This function is for internal use only.
     *
     * Deletes an inverse property from a resource.
     *
     * @ignore
     */
    protected function deleteInverse($resource, $property, $value)
    {
        if (isset($this->revIndex[$resource])) {
            foreach ($this->revIndex[$resource][$property] as $k => $v) {
                if ($v['value'] === $value) {
                    unset($this->revIndex[$resource][$property][$k]);
                }
            }
            if (count($this->revIndex[$resource][$property]) == 0) {
                unset($this->revIndex[$resource][$property]);
            }
            if (count($this->revIndex[$resource]) == 0) {
                unset($this->revIndex[$resource]);
            }
        }
    }

    /** Check if the graph contains any statements
     *
     * @return boolean True if the graph contains no statements
     */
    public function isEmpty()
    {
        return count($this->index) == 0;
    }

    /** Get a list of all the shortened property names (qnames) for a resource.
     *
     * This method will return an empty array if the resource has no properties.
     *
     * @return array            Array of shortened URIs
     */
    public function properties($resource)
    {
        $this->checkResourceParam($resource);

        $properties = array();
        if (isset($this->index[$resource])) {
            foreach ($this->index[$resource] as $property => $value) {
                $short = EasyRdf_Namespace::shorten($property);
                if ($short) {
                    $properties[] = $short;
                }
            }
        }
        return $properties;
    }

    /** Get a list of the full URIs for the properties of a resource.
     *
     * This method will return an empty array if the resource has no properties.
     *
     * @return array            Array of full URIs
     */
    public function propertyUris($resource)
    {
        $this->checkResourceParam($resource);

        if (isset($this->index[$resource])) {
            return array_keys($this->index[$resource]);
        } else {
            return array();
        }
    }

    /** Get a list of the full URIs for the properties that point to a resource.
     *
     * @return array   Array of full property URIs
     */
    public function reversePropertyUris($resource)
    {
        $this->checkResourceParam($resource);

        if (isset($this->revIndex[$resource])) {
            return array_keys($this->revIndex[$resource]);
        } else {
            return array();
        }
    }

    /** Check to see if a property exists for a resource.
     *
     * This method will return true if the property exists.
     * If the value parameter is given, then it will only return true
     * if the value also exists for that property.
     *
     * By providing a value parameter you can use this function to check
     * to see if a triple exists in the graph.
     *
     * @param  mixed   $resource The resource to check
     * @param  string  $property The name of the property (e.g. foaf:name)
     * @param  mixed   $value    An optional value of the property
     * @return boolean           True if value the property exists.
     */
    public function hasProperty($resource, $property, $value = null)
    {
        $this->checkResourceParam($resource);
        $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;
        }

        if (isset($index[$resource][$property])) {
            if (is_null($value)) {
                return true;
            } else {
                foreach ($index[$resource][$property] as $v) {
                    if ($v == $value) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /** Serialise the graph into RDF
     *
     * The $format parameter can be an EasyRdf_Format object, a
     * format name, a mime type or a file extension.
     *
     * Example:
     *   $turtle = $graph->serialise('turtle');
     *
     * @param  mixed  $format  The format to serialise to
     * @return mixed  The serialised graph
     */
    public function serialise($format)
    {
        if (!$format instanceof EasyRdf_Format) {
            $format = EasyRdf_Format::getFormat($format);
        }
        $serialiser = $format->newSerialiser();
        return $serialiser->serialise($this, $format->getName());
    }

    /** Return a human readable view of all the resources in the graph
     *
     * This method is intended to be a debugging aid and will
     * return a pretty-print view of all the resources and their
     * properties.
     *
     * @param  boolean  $html  Set to true to format the dump using HTML
     * @return string
     */
    public function dump($html = true)
    {
        $result = '';
        if ($html) {
            $result .= "<div style='font-family:arial; font-weight: bold; padding:0.5em; ".
                   "color: black; background-color:lightgrey;border:dashed 1px grey;'>".
                   "Graph: ". $this->uri . "</div>\n";
        } else {
            $result .= "Graph: ". $this->uri . "\n";
        }

        foreach ($this->index as $resource => $properties) {
            $result .= $this->dumpResource($resource, $html);
        }
        return $result;
    }

    /** Return a human readable view of a resource and its properties
     *
     * This method is intended to be a debugging aid and will
     * print a resource and its properties.
     *
     * @param  mixed    $resource  The resource to dump
     * @param  boolean  $html      Set to true to format the dump using HTML
     * @return string
     */
    public function dumpResource($resource, $html = true)
    {
        $this->checkResourceParam($resource, true);

        if (isset($this->index[$resource])) {
            $properties = $this->index[$resource];
        } else {
            return '';
        }

        $plist = array();
        foreach ($properties as $property => $values) {
            $olist = array();
            foreach ($values as $value) {
                if ($value['type'] == 'literal') {
                    $olist []= EasyRdf_Utils::dumpLiteralValue($value, $html, 'black');
                } else {
                    $olist []= EasyRdf_Utils::dumpResourceValue($value['value'], $html, 'blue');
                }
            }

            $pstr = EasyRdf_Namespace::shorten($property);
            if ($pstr == null) {
                $pstr = $property;
            }
            if ($html) {
                $plist []= "<span style='font-size:130%'>&rarr;</span> ".
                           "<span style='text-decoration:none;color:green'>".
                           htmlentities($pstr) . "</span> ".
                           "<span style='font-size:130%'>&rarr;</span> ".
                           join(", ", $olist);
            } else {
                $plist []= "  -> $pstr -> " . join(", ", $olist);
            }
        }

        if ($html) {
            return "<div id='".htmlentities($resource)."' " .
                   "style='font-family:arial; padding:0.5em; ".
                   "background-color:lightgrey;border:dashed 1px grey;'>\n".
                   "<div>".EasyRdf_Utils::dumpResourceValue($resource, true, 'blue')." ".
                   "<span style='font-size: 0.8em'>(".
                   $this->classForResource($resource).")</span></div>\n".
                   "<div style='padding-left: 3em'>\n".
                   "<div>".join("</div>\n<div>", $plist)."</div>".
                   "</div></div>\n";
        } else {
            return $resource." (".$this->classForResource($resource).")\n" .
                   join("\n", $plist) . "\n\n";
        }
    }

    /** Get the resource type of the graph
     *
     * The type will be a shortened URI as a string.
     * If the graph has multiple types then the type returned
     * may be arbitrary.
     * This method will return null if the resource has no type.
     *
     * @return string A type assocated with the resource (e.g. foaf:Document)
     */
    public function type($resource = null)
    {
        $this->checkResourceParam($resource, true);

        if ($resource) {
            $type = $this->get($resource, 'rdf:type', 'resource');
            if ($type) {
                return EasyRdf_Namespace::shorten($type);
            }
        }

        return null;
    }

    /** Get the resource type of the graph as a EasyRdf_Resource
     *
     * If the graph has multiple types then the type returned
     * may be arbitrary.
     * This method will return null if the resource has no type.
     *
     * @return object EasyRdf_Resource  A type assocated with the resource
     */
    public function typeAsResource($resource = null)
    {
        $this->checkResourceParam($resource, true);

        if ($resource) {
            return $this->get($resource, 'rdf:type', 'resource');
        }

        return null;
    }

    /** Get a list of types for a resource
     *
     * The types will each be a shortened URI as a string.
     * This method will return an empty array if the resource has no types.
     *
     * If $resource is null, then it will get the types for the URI of the graph.
     *
     * @return array All types assocated with the resource (e.g. foaf:Person)
     */
    public function types($resource = null)
    {
        $this->checkResourceParam($resource, true);

        $types = array();
        if ($resource) {
            foreach ($this->all($resource, 'rdf:type', 'resource') as $type) {
                $types[] = EasyRdf_Namespace::shorten($type);
            }
        }

        return $types;
    }

    /** Check if a resource is of the specified type
     *
     * @param  string  $resource The resource to check the type of
     * @param  string  $type     The type to check (e.g. foaf:Person)
     * @return boolean           True if resource is of specified type
     */
    public function isA($resource, $type)
    {
        $this->checkResourceParam($resource, true);

        $type = EasyRdf_Namespace::expand($type);
        foreach ($this->all($resource, 'rdf:type', 'resource') as $t) {
            if ($t->getUri() == $type) {
                return true;
            }
        }
        return false;
    }

    /** Add one or more rdf:type properties to a resource
     *
     * @param  string  $resource The resource to add the type to
     * @param  string  $types    One or more types to add (e.g. foaf:Person)
     * @return integer           The number of types added
     */
    public function addType($resource, $types)
    {
        $this->checkResourceParam($resource, true);

        if (!is_array($types)) {
            $types = array($types);
        }

        $count = 0;
        foreach ($types as $type) {
            $type = EasyRdf_Namespace::expand($type);
            $count += $this->add($resource, 'rdf:type', array('type' => 'uri', 'value' => $type));
        }

        return $count;
    }

    /** Change the rdf:type property for a resource
     *
     * Note that if the resource object has already previously
     * been created, then the PHP class of the resource will not change.
     *
     * @param  string  $resource The resource to change the type of
     * @param  string  $type     The new type (e.g. foaf:Person)
     * @return integer           The number of types added
     */
    public function setType($resource, $type)
    {
        $this->checkResourceParam($resource, true);

        $this->delete($resource, 'rdf:type');
        return $this->addType($resource, $type);
    }

    /** Get a human readable label for a resource
     *
     * This method will check a number of properties for a resource
     * (in the order: skos:prefLabel, rdfs:label, foaf:name, dc:title)
     * and return an approriate first that is available. If no label
     * is available then it will return null.
     *
     * @return string A label for the resource.
     */
    public function label($resource = null, $lang = null)
    {
        $this->checkResourceParam($resource, true);

        if ($resource) {
            return $this->get(
                $resource,
                'skos:prefLabel|rdfs:label|foaf:name|dc:title|dc11:title',
                'literal',
                $lang
            );
        } else {
            return null;
        }
    }

    /** Get the primary topic of the graph
     *
     * @return EasyRdf_Resource The primary topic of the document.
     */
    public function primaryTopic($resource = null)
    {
        $this->checkResourceParam($resource, true);

        if ($resource) {
            return $this->get(
                $resource,
                'foaf:primaryTopic|^foaf:isPrimaryTopicOf',
                'resource'
            );
        } else {
            return null;
        }
    }

    /** Returns the graph as a RDF/PHP associative array
     *
     * @return array The contents of the graph as an array.
     */
    public function toArray()
    {
        return $this->index;
    }

    /** Calculates the number of triples in the graph
     *
     * @return integer The number of triples in the graph.
     */
    public function countTriples()
    {
        $count = 0;
        foreach ($this->index as $resource) {
            foreach ($resource as $property => $values) {
                $count += count($values);
            }
        }
        return $count;
    }

    /** Magic method to return URI of resource when casted to string
     *
     * @return string The URI of the resource
     */
    public function __toString()
    {
        return $this->uri == null ? '' : $this->uri;
    }

    /** Magic method to get a property of the graph
     *
     * Note that only properties in the default namespace can be accessed in this way.
     *
     * Example:
     *   $value = $graph->title;
     *
     * @see EasyRdf_Namespace::setDefault()
     * @param  string $name The name of the property
     * @return string       A single value for the named property
     */
    public function __get($name)
    {
        return $this->get($this->uri, $name);
    }

    /** Magic method to set the value for a property of the graph
     *
     * Note that only properties in the default namespace can be accessed in this way.
     *
     * Example:
     *   $graph->title = 'Title';
     *
     * @see EasyRdf_Namespace::setDefault()
     * @param  string $name The name of the property
     * @param  string $value The value for the property
     */
    public function __set($name, $value)
    {
        return $this->set($this->uri, $name, $value);
    }

    /** Magic method to check if a property exists
     *
     * Note that only properties in the default namespace can be accessed in this way.
     *
     * Example:
     *   if (isset($graph->title)) { blah(); }
     *
     * @see EasyRdf_Namespace::setDefault()
     * @param string $name The name of the property
     */
    public function __isset($name)
    {
        return $this->hasProperty($this->uri, $name);
    }

    /** Magic method to delete a property of the graph
     *
     * Note that only properties in the default namespace can be accessed in this way.
     *
     * Example:
     *   unset($graph->title);
     *
     * @see EasyRdf_Namespace::setDefault()
     * @param string $name The name of the property
     */
    public function __unset($name)
    {
        return $this->delete($this->uri, $name);
    }
}