summaryrefslogtreecommitdiffstats
path: root/core/vendor/easyrdf/easyrdf/lib/EasyRdf/Sparql/Result.php
blob: 6bc7f62aae526459fc58dbada7d85722c96729c3 (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
<?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$
 */

/**
 * Class for returned for SPARQL SELECT and ASK query responses.
 *
 * @package    EasyRdf
 * @copyright  Copyright (c) 2009-2012 Nicholas J Humfrey
 * @license    http://www.opensource.org/licenses/bsd-license.php
 */
class EasyRdf_Sparql_Result extends ArrayIterator
{
    private $type = null;
    private $boolean = null;

    private $ordered = null;
    private $distinct = null;
    private $fields = array();

    /** A constant for the SPARQL Query Results XML Format namespace */
    const SPARQL_XML_RESULTS_NS = 'http://www.w3.org/2005/sparql-results#';

    /** Create a new SPARQL Result object
     *
     * You should not normally need to create a SPARQL result
     * object directly - it will be constructed automatically
     * for you by EasyRdf_Sparql_Client.
     *
     * @param string $data      The SPARQL result body
     * @param string $mimeType  The MIME type of the result
     */
    public function __construct($data, $mimeType)
    {
        if ($mimeType == 'application/sparql-results+xml') {
            return $this->parseXml($data);
        } elseif ($mimeType == 'application/sparql-results+json') {
            return $this->parseJson($data);
        } else {
            throw new EasyRdf_Exception(
                "Unsupported SPARQL Query Results format: $mimeType"
            );
        }
    }

    /** Get the query result type (boolean/bindings)
     *
     * ASK queries return a result of type 'boolean'.
     * SELECT query return a result of type 'bindings'.
     *
     * @return string The query result type.
     */
    public function getType()
    {
        return $this->type;
    }

    /** Return the boolean value of the query result
     *
     * If the query was of type boolean then this method will
     * return either true or false. If the query was of some other
     * type then this method will return null.
     *
     * @return boolean The result of the query.
     */
    public function getBoolean()
    {
        return $this->boolean;
    }

    /** Return true if the result of the query was true.
     *
     * @return boolean True if the query result was true.
     */
    public function isTrue()
    {
        return $this->boolean == true;
    }

    /** Return false if the result of the query was false.
     *
     * @return boolean True if the query result was false.
     */
    public function isFalse()
    {
        return $this->boolean == false;
    }

    /** Return the number of fields in a query result of type bindings.
     *
     * @return integer The number of fields.
     */
    public function numFields()
    {
        return count($this->fields);
    }

    /** Return the number of rows in a query result of type bindings.
     *
     * @return integer The number of rows.
     */
    public function numRows()
    {
        return count($this);
    }

    /** Get the field names in a query result of type bindings.
     *
     * @return array The names of the fields in the result.
     */
    public function getFields()
    {
        return $this->fields;
    }

    /** Return a human readable view of the query result.
     *
     * This method is intended to be a debugging aid and will
     * return a pretty-print view of the query result.
     *
     * @param  bool  $html  Set to true to format the dump using HTML
     */
    public function dump($html = true)
    {
        if ($this->type == 'bindings') {
            $result = '';
            if ($html) {
                $result .= "<table class='sparql-results' style='border-collapse:collapse'>";
                $result .= "<tr>";
                foreach ($this->fields as $field) {
                    $result .= "<th style='border:solid 1px #000;padding:4px;".
                               "vertical-align:top;background-color:#eee;'>".
                               "?$field</th>";
                }
                $result .= "</tr>";
                foreach ($this as $row) {
                    $result .= "<tr>";
                    foreach ($this->fields as $field) {
                        $result .= "<td style='border:solid 1px #000;padding:4px;".
                                   "vertical-align:top'>".
                                   $row->$field->dumpValue($html)."</td>";
                    }
                    $result .= "</tr>";
                }
                $result .= "</table>";
            } else {
                // First calculate the width of each comment
                $colWidths = array();
                foreach ($this->fields as $field) {
                    $colWidths[$field] = strlen($field);
                }

                $textData = array();
                foreach ($this as $row) {
                    $textRow = array();
                    foreach ($row as $k => $v) {
                        $textRow[$k] = $v->dumpValue(false);
                        $width = strlen($textRow[$k]);
                        if ($colWidths[$k] < $width) {
                            $colWidths[$k] = $width;
                        }
                    }
                    $textData[] = $textRow;
                }

                // Create a horizontal rule
                $hr = "+";
                foreach ($colWidths as $k => $v) {
                    $hr .= "-".str_repeat('-', $v).'-+';
                }

                // Output the field names
                $result .= "$hr\n|";
                foreach ($this->fields as $field) {
                    $result .= ' '.str_pad("?$field", $colWidths[$field]).' |';
                }

                // Output each of the rows
                $result .= "\n$hr\n";
                foreach ($textData as $textRow) {
                    $result .= '|';
                    foreach ($textRow as $k => $v) {
                        $result .= ' '.str_pad($v, $colWidths[$k]).' |';
                    }
                    $result .= "\n";
                }
                $result .= "$hr\n";

            }
            return $result;
        } elseif ($this->type == 'boolean') {
            $str = ($this->boolean ? 'true' : 'false');
            if ($html) {
                return "<p>Result: <span style='font-weight:bold'>$str</span></p>";
            } else {
                return "Result: $str";
            }
        } else {
            throw new EasyRdf_Exception(
                "Failed to dump SPARQL Query Results format, unknown type: ". $this->type
            );
        }
    }

    /** Create a new EasyRdf_Resource or EasyRdf_Literal depending
     *  on the type of data passed in.
     *
     * @ignore
     */
    protected function newTerm($data)
    {
        switch($data['type']) {
            case 'bnode':
                return new EasyRdf_Resource('_:'.$data['value']);
            case 'uri':
                return new EasyRdf_Resource($data['value']);
            case 'literal':
            case 'typed-literal':
                return EasyRdf_Literal::create($data);
            default:
                throw new EasyRdf_Exception(
                    "Failed to parse SPARQL Query Results format, unknown term type: ".
                    $data['type']
                );
        }
    }

    /** Parse a SPARQL result in the XML format into the object.
     *
     * @ignore
     */
    protected function parseXml($data)
    {
        $doc = new DOMDocument();
        $doc->loadXML($data);

        # Check for valid root node.
        if ($doc->hasChildNodes() == false or
            $doc->childNodes->length != 1 or
            $doc->firstChild->nodeName != 'sparql' or
            $doc->firstChild->namespaceURI != self::SPARQL_XML_RESULTS_NS) {
            throw new EasyRdf_Exception(
                "Incorrect root node in SPARQL XML Query Results format"
            );
        }

        # Is it the result of an ASK query?
        $boolean = $doc->getElementsByTagName('boolean');
        if ($boolean->length) {
            $this->type = 'boolean';
            $value = $boolean->item(0)->nodeValue;
            $this->boolean = $value == 'true' ? true : false;
            return;
        }

        # Get a list of variables from the header
        $head = $doc->getElementsByTagName('head');
        if ($head->length) {
            $variables = $head->item(0)->getElementsByTagName('variable');
            foreach ($variables as $variable) {
                $this->fields[] = $variable->getAttribute('name');
            }
        }

        # Is it the result of a SELECT query?
        $resultstag = $doc->getElementsByTagName('results');
        if ($resultstag->length) {
            $this->type = 'bindings';
            $results = $resultstag->item(0)->getElementsByTagName('result');
            foreach ($results as $result) {
                $bindings = $result->getElementsByTagName('binding');
                $t = new stdClass();
                foreach ($bindings as $binding) {
                    $key = $binding->getAttribute('name');
                    foreach ($binding->childNodes as $node) {
                        if ($node->nodeType != XML_ELEMENT_NODE) {
                            continue;
                        }
                        $t->$key = $this->newTerm(
                            array(
                                'type' => $node->nodeName,
                                'value' => $node->nodeValue,
                                'lang' => $node->getAttribute('xml:lang'),
                                'datatype' => $node->getAttribute('datatype')
                            )
                        );
                        break;
                    }
                }
                $this[] = $t;
            }
            return $this;
        }

        throw new EasyRdf_Exception(
            "Failed to parse SPARQL XML Query Results format"
        );
    }

    /** Parse a SPARQL result in the JSON format into the object.
     *
     * @ignore
     */
    protected function parseJson($data)
    {
        // Decode JSON to an array
        $data = json_decode($data, true);

        if (isset($data['boolean'])) {
            $this->type = 'boolean';
            $this->boolean = $data['boolean'];
        } elseif (isset($data['results'])) {
            $this->type = 'bindings';
            if (isset($data['head']['vars'])) {
                $this->fields = $data['head']['vars'];
            }

            foreach ($data['results']['bindings'] as $row) {
                $t = new stdClass();
                foreach ($row as $key => $value) {
                    $t->$key = $this->newTerm($value);
                }
                $this[] = $t;
            }
        } else {
            throw new EasyRdf_Exception(
                "Failed to parse SPARQL JSON Query Results format"
            );
        }
    }

    /** Magic method to return value of the result to string
     *
     * If this is a boolean result then it will return 'true' or 'false'.
     * If it is a bindings type, then it will dump as a text based table.
     *
     * @return string A string representation of the result.
     */
    public function __toString()
    {
        if ($this->type == 'boolean') {
            return $this->boolean ? 'true' : 'false';
        } else {
            return $this->dump(false);
        }
    }
}