This repository has been archived by the owner on Aug 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRdfHelpers.php
346 lines (297 loc) · 10.4 KB
/
RdfHelpers.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
<?php
/*
* This file is part of Saft.
*
* (c) Konrad Abicht <hi@inspirito.de>
* (c) Natanael Arndt <arndt@informatik.uni-leipzig.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Saft\Rdf;
/**
* Class which provides useful methods for RDF related operations, for instance node creation or
* URI checks.
*
* @api
*
* @since 0.9
*/
class RdfHelpers
{
/**
* @param string $s
*
* @return string encoded string for n-quads
*/
public function encodeStringLitralForNQuads($s)
{
$s = str_replace('\\', '\\\\', $s);
$s = str_replace("\t", '\t', $s);
$s = str_replace("\n", '\n', $s);
$s = str_replace("\r", '\r', $s);
$s = str_replace('"', '\"', $s);
return $s;
}
/**
* Returns given Node instance in SPARQL format, which is in NQuads or as Variable.
*
* @param Node $node node instance to format
* @param string $var The variablename, which should be used, if the node is not concrete
*
* @return string either NQuad notation (if node is concrete) or as variable
*/
public function getNodeInSparqlFormat(Node $node, $var = null)
{
if ($node->isConcrete()) {
return $node->toNQuads();
}
if (null !== $var) {
return '?'.$var;
} else {
return '?'.uniqid('tempVar');
}
}
/**
* Get type for a given SPARQL query.
*
* @param string $query
*
* @return string Type, which is either askQuery, describeQuery, graphQuery, updateQuery or selectQuery
*
* @throws \Exception if unknown query type
*/
public function getQueryType($query)
{
/**
* First we get rid of all PREFIX information.
*/
$adaptedQuery = preg_replace('/PREFIX\s+[a-z0-9\-]+\:\s*\<[a-z0-9\:\/\.\#\-\~\_]+\>/si', '', $query);
// remove whitespace lines and trailing whitespaces
$adaptedQuery = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", '', trim($adaptedQuery));
// only lower chars
$adaptedQuery = strtolower($adaptedQuery);
/**
* After we know the type, we initiate the according class and return it.
*/
$firstPart = substr($adaptedQuery, 0, 3);
switch ($firstPart) {
// ASK
case 'ask':
return 'askQuery';
// CONSTRUCT
case 'con':
return 'constructQuery';
// DESCRIBE
case 'des':
return 'describeQuery';
/*
* If we land here, we have to use a higher range of characters
*/
default:
$firstPart = substr($adaptedQuery, 0, 6);
switch ($firstPart) {
// CLEAR GRAPH
case 'clear ':
return 'graphQuery';
// CREATE GRAPH
// CREATE SILENT GRAPH
case 'create':
return 'graphQuery';
// DELETE DATA
case 'delete':
return 'updateQuery';
// DROP GRAPH
case 'drop g':
return 'graphQuery';
// DROP SILENT GRAPH
case 'drop s':
return 'graphQuery';
// INSERT DATA
// INSERT INTO
case 'insert':
return 'updateQuery';
// SELECT
case 'select':
return 'selectQuery';
default:
// check if query is of type: WITH <http:// ... > DELETE { ... } WHERE { ... }
// TODO make it more precise
if (false !== strpos($adaptedQuery, 'with')
&& false !== strpos($adaptedQuery, 'delete')
&& false !== strpos($adaptedQuery, 'where')) {
return 'updateQuery';
// check if query is of type: WITH <http:// ... > DELETE { ... }
// TODO make it more precise
} elseif (false !== strpos($adaptedQuery, 'with')
&& false !== strpos($adaptedQuery, 'delete')) {
return 'updateQuery';
}
}
}
throw new \Exception('Unknown query type "'.$firstPart.'" for query: '.$adaptedQuery);
}
/**
* Returns the regex string to get a node from a triple/quad.
*
* @param bool $useVariables optional, default is false
* @param bool $useNamespacedUri optional, default is false
*
* @return string
*/
public function getRegexStringForNodeRecognition(
$useBlankNode = false,
$useNamespacedUri = false,
$useTypedString = false,
$useLanguagedString = false,
$useSimpleString = false,
$useSimpleNumber = false,
$useVariables = false
) {
$regex = '(<([a-z]{2,}:[^\s]*)>)'; // e.g. <http://foobar/a>
if (true == $useBlankNode) {
$regex .= '|(_:([a-z0-9A-Z_]+))'; // e.g. _:foobar
}
if (true == $useNamespacedUri) {
$regex .= '|(([a-z0-9]+)\:([a-z0-9]+))'; // e.g. rdfs:label
}
if (true == $useTypedString) {
// e.g. "Foo"^^<http://www.w3.org/2001/XMLSchema#string>
$regex .= '|(\"(.*?)\"\^\^\<([^\s]+)\>)';
}
if (true == $useLanguagedString) {
$regex .= '|(\"(.*?)\"\@([a-z\-]{2,}))'; // e.g. "Foo"@en
}
if (true == $useSimpleString) {
$regex .= '|(\"(.*?)\")'; // e.g. "Foo"
}
if (true == $useSimpleNumber) {
$regex .= '|([0-9]{1,})'; // e.g. 42
}
if (true == $useVariables) {
$regex .= '|(\?[a-z0-9\_]+)'; // e.g. ?s
}
return $regex;
}
/**
* Returns the value (or URI or ID) for a given node.
*
* @param Node $node Node you want the value of. Can be of type NamedNode, BlankNode or Literal.
*
* @return string|null
*/
public function getValueForNode(Node $node)
{
if ($node->isNamed()) {
return $node->getUri();
} elseif ($node->isLiteral()) {
return $node->getValue();
} elseif ($node->isBlank()) {
return $node->getBlankId();
} else {
return null;
}
}
/**
* @param string $stringToCheck
*
* @return null|string
*/
public function guessFormat($stringToCheck)
{
if (false == is_string($stringToCheck)) {
throw new \Exception('Invalid $stringToCheck value given. It needs to be a string.');
}
$short = substr($stringToCheck, 0, 1024);
// n-triples/n-quads
if (0 < preg_match('/^<.+>/i', $short, $matches)) {
return 'n-triples';
// RDF/XML
} elseif (0 < preg_match('/<rdf:/i', $short, $matches)) {
return 'rdf-xml';
// turtle
} elseif (0 < preg_match('/@prefix\s|@base\s/i', $short, $matches)) {
return 'turtle';
}
return null;
}
/**
* Checks if a given string is a blank node ID. Blank nodes are usually structured like
* _:foo, whereas _: comes first always.
*
* @param string $string string to check if its a blank node ID or not
*
* @return bool true if given string is a valid blank node ID, false otherwise
*/
public function simpleCheckBlankNodeId($string)
{
return '_:' == substr($string, 0, 2);
}
/**
* Checks the general syntax of a given URI. Protocol-specific syntaxes are not checked. Instead, only
* characters disallowed an all URIs lead to a rejection of the check. Use this function, if you need a
* basic check and if performance is an issuse. In case you need a more precise check, that function is
* not recommended.
*
* @param string $string string to check if its a URI or not
*
* @return bool true if given string is a valid URI, false otherwise
*
* @api
*
* @since 0.1
*/
public function simpleCheckURI($string)
{
$regEx = '/^([a-z]{2,}:[^\s]*)$/';
return 1 === preg_match($regEx, (string) $string);
}
/**
* Returns the Statement-Data in sparql-Format.
*
* @param StatementIterator|array $statements list of statements to format as SPARQL string
* @param Node $graph use if each statement is a triple and to use another graph as the default
*
* @return string Statement data in SPARQL format
*/
public function statementIteratorToSparqlFormat($statements, Node $graph = null)
{
$query = '';
foreach ($statements as $statement) {
if ($statement instanceof Statement) {
$con = $this->getNodeInSparqlFormat($statement->getSubject()).' '.
$this->getNodeInSparqlFormat($statement->getPredicate()).' '.
$this->getNodeInSparqlFormat($statement->getObject()).' . ';
$graphToUse = $graph;
if ($graph == null && $statement->isQuad()) {
$graphToUse = $statement->getGraph();
}
if (null !== $graphToUse) {
$sparqlString = 'Graph '.self::getNodeInSparqlFormat($graphToUse).' {'.$con.'}';
} else {
$sparqlString = $con;
}
$query .= $sparqlString.' ';
} else {
throw new \Exception('Not a Statement instance');
}
}
return $query;
}
/**
* Returns the Statement-Data in sparql-Format.
*
* @param array $statements list of statements to format as SPARQL string
* @param string $graphUri Use if each statement is a triple and to use another graph as
* the default. (optional)
*
* @return string Statement data in SPARQL format
*/
public function statementsToSparqlFormat(array $statements, Node $graph = null)
{
return $this->statementIteratorToSparqlFormat(
$statements,
$graph
);
}
}