Completed
Push — master ( 3a9c1f...b05d7f )
by Henri
03:36
created

Model::getVocabularyByGraph()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 21
rs 8.7624
cc 5
eloc 13
nc 8
nop 2
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 20 and the first side effect is on line 11.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Copyright (c) 2012 Aalto University and University of Helsinki
4
 * MIT License
5
 * see LICENSE.txt for more information
6
 */
7
8
/**
9
 * Setting some often needed namespace prefixes
10
 */
11
EasyRdf_Namespace::set('skosmos', 'http://purl.org/net/skosmos#');
12
EasyRdf_Namespace::set('void', 'http://rdfs.org/ns/void#');
13
EasyRdf_Namespace::set('skosext', 'http://purl.org/finnonto/schema/skosext#');
14
EasyRdf_Namespace::set('isothes', 'http://purl.org/iso25964/skos-thes#');
15
16
/**
17
 * Model provides access to the data.
18
 * @property EasyRdf_Graph $graph
19
 */
20
class Model
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
21
{
22
    /** EasyRdf_Graph graph instance */
23
    private $graph;
24
    /** cache for Vocabulary objects */
25
    private $all_vocabularies = null;
26
    /** cache for Vocabulary objects */
27
    private $vocabs_by_graph = null;
28
    /** cache for Vocabulary objects */
29
    private $vocabs_by_urispace = null;
30
    /** how long to store retrieved URI information in APC cache */
31
    private $URI_FETCH_TTL = 86400; // 1 day
32
    private $global_config = '';
33
34
    /**
35
     * Initializes the Model object
36
     */
37
    public function __construct($config)
38
    {
39
        $this->global_config = $config;
40
        $this->initializeVocabularies();
41
    }
42
43
    public function getConfig() {
44
      return $this->global_config;
45
    }
46
47
    /**
48
     * Initializes the configuration from the vocabularies.ttl file
49
     */
50
    private function initializeVocabularies()
51
    {
52
        if (!file_exists($this->getConfig()->getVocabularyConfigFile())) {
0 ignored issues
show
Bug introduced by
The method getVocabularyConfigFile cannot be called on $this->getConfig() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
53
            throw new Exception($this->getConfig()->getVocabularyConfigFile() . ' is missing, please provide one.');
0 ignored issues
show
Bug introduced by
The method getVocabularyConfigFile cannot be called on $this->getConfig() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
54
        }
55
56
        try {
57
            // use APC user cache to store parsed vocabularies.ttl configuration
58
            if (function_exists('apc_store') && function_exists('apc_fetch')) {
59
                $key = realpath($this->getConfig()->getVocabularyConfigFile()) . ", " . filemtime($this->getConfig()->getVocabularyConfigFile());
0 ignored issues
show
Bug introduced by
The method getVocabularyConfigFile cannot be called on $this->getConfig() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
60
                $this->graph = apc_fetch($key);
61
                if ($this->graph === false) { // was not found in cache
62
                    $this->graph = new EasyRdf_Graph();
63
                    $this->graph->parse(file_get_contents($this->getConfig()->getVocabularyConfigFile()));
0 ignored issues
show
Bug introduced by
The method getVocabularyConfigFile cannot be called on $this->getConfig() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
64
                    apc_store($key, $this->graph);
65
                }
66
            } else { // APC not available, parse on every request
67
                $this->graph = new EasyRdf_Graph();
68
                $this->graph->parse(file_get_contents($this->getConfig()->getVocabularyConfigFile()));
0 ignored issues
show
Bug introduced by
The method getVocabularyConfigFile cannot be called on $this->getConfig() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
69
            }
70
        } catch (Exception $e) {
71
            echo "Error: " . $e->getMessage();
72
        }
73
    }
74
75
    /**
76
     * Return the version of this Skosmos installation, or "unknown" if
77
     * it cannot be determined. The version information is based on Git tags.
78
     * @return string version
79
     */
80
    public function getVersion()
81
    {
82
        $ver = null;
83
        if (file_exists('.git')) {
84
            $ver = shell_exec('git describe --tags');
85
        }
86
87
        if ($ver === null) {
88
            return "unknown";
89
        }
90
91
        return $ver;
92
    }
93
94
    /**
95
     * Return all the vocabularies available.
96
     * @param boolean $categories whether you want everything included in a subarray of
97
     * a category.
98
     * @param boolean $shortname set to true if you want the vocabularies sorted by 
99
     * their shortnames instead of ther titles.
100
     */
101
    public function getVocabularyList($categories = true, $shortname = false)
102
    {
103
        $cats = $this->getVocabularyCategories();
104
        $ret = array();
105
        foreach ($cats as $cat) {
106
            $catlabel = $cat->getTitle();
107
108
            // find all the vocabs in this category
109
            $vocs = array();
110
            foreach ($cat->getVocabularies() as $voc) {
111
                $vocs[$shortname ? $voc->getConfig()->getShortname() : $voc->getConfig()->getTitle()] = $voc;
112
            }
113
            uksort($vocs, 'strcoll');
114
115
            if (sizeof($vocs) > 0 && $categories) {
116
                $ret[$catlabel] = $vocs;
117
            } elseif (sizeof($vocs) > 0) {
118
                $ret = array_merge($ret, $vocs);
119
            }
120
121
        }
122
123
        if (!$categories) {
124
            uksort($ret, 'strcoll');
125
        }
126
127
        return $ret;
128
    }
129
130
    /**
131
     * Return all types (RDFS/OWL classes) present in the specified vocabulary or all vocabularies.
132
     * @return array Array with URIs (string) as key and array of (label, superclassURI) as value
133
     */
134
    public function getTypes($vocid = null, $lang = null)
135
    {
136
        $sparql = (isset($vocid)) ? $this->getVocabulary($vocid)->getSparql() : $this->getDefaultSparql();
137
        $result = $sparql->queryTypes($lang);
138
139
        foreach ($result as $uri => $values) {
140
            if (empty($values)) {
141
                $shorteneduri = EasyRdf_Namespace::shorten($uri);
142
                if ($shorteneduri !== null) {
143
                    $trans = gettext($shorteneduri);
144
                    if ($trans) {
145
                        $result[$uri] = array('label' => $trans);
146
                    }
147
                }
148
            }
149
        }
150
151
        return $result;
152
    }
153
154
    /**
155
     * Return the languages present in the configured vocabularies.
156
     * @return array Array with lang codes (string)
157
     */
158
    public function getLanguages($lang)
159
    {
160
        $vocabs = $this->getVocabularyList(false);
161
        $ret = array();
162
        foreach ($vocabs as $vocab) {
163
            foreach ($vocab->getConfig()->getLanguages() as $langcode) {
164
                $langlit = Punic\Language::getName($langcode, $lang);
165
                $ret[$langlit] = $langcode;
166
            }
167
        }
168
        ksort($ret);
169
        return array_unique($ret);
170
    }
171
172
    /**
173
     * returns a concept's RDF data in downloadable format
174
     * @param string $vocid vocabulary id, or null for global data (from all vocabularies)
175
     * @param string $uri concept URI
176
     * @param string $format the format in which you want to get the result, currently this function supports
177
     * text/turtle, application/rdf+xml and application/json
178
     * @return string RDF data in the requested serialization
179
     */
180
    public function getRDF($vocid, $uri, $format)
181
    {
182
183
        if ($format == 'text/turtle') {
184
            $retform = 'turtle';
185
            $serialiser = new EasyRdf_Serialiser_Turtle();
186
        } elseif ($format == 'application/ld+json' || $format == 'application/json') {
187
            $retform = 'jsonld'; // serve JSON-LD for both JSON-LD and plain JSON requests
188
            $serialiser = new EasyRdf_Serialiser_JsonLd();
189
        } else {
190
            $retform = 'rdfxml';
191
            $serialiser = new EasyRdf_Serialiser_RdfXml();
192
        }
193
194
        if ($vocid !== null) {
195
            $vocab = $this->getVocabulary($vocid);
196
            $sparql = $vocab->getSparql();
197
            $arrayClass = $vocab->getConfig()->getArrayClassURI();
198
            $vocabs = array($vocab);
199
        } else {
200
            $sparql = $this->getDefaultSparql();
201
            $arrayClass = null;
202
            $vocabs = null;
203
        }
204
        $result = $sparql->queryConceptInfo($uri, $arrayClass, $vocabs, true);
205
206
        return $serialiser->serialise($result, $retform);
207
    }
208
209
    /**
210
     * Makes a SPARQL-query to the endpoint that retrieves concept
211
     * references as it's search results.
212
     * @param string $term the term that is looked for eg. 'cat'.
213
     * @param mixed $vocids vocabulary id eg. 'yso', array of such ids for multi-vocabulary search, or null for global search.
214
     * @param string $lang language code to show labels in, eg. 'fi' for Finnish.
215
     * @param string $search_lang language code used for matching, eg. 'fi' for Finnish, null for any language
216
     * @param string $type limit search to concepts of the given type
217
     * @param string $parent limit search to concepts which have the given concept as parent in the transitive broader hierarchy
218
     * @param string $group limit search to concepts which are in the given group
219
     * @param int $offset optional parameter for search offset.
220
     * @param int $limit optional paramater for maximum amount of results.
221
     * @param boolean $hidden include matches on hidden labels (default: true).
222
     * @param array $fields extra fields to include in the result (array of strings). (default: null = none)
223
     * @return array search results
224
     */
225
    public function searchConcepts($term, $vocids, $lang, $search_lang, $type = null, $parent = null, $group = null, $offset = 0, $limit = null, $hidden = true, $fields = null)
226
    {
227
        if ($limit === null) {
228
            $limit = $this->getConfig()->getDefaultSearchLimit();
0 ignored issues
show
Bug introduced by
The method getDefaultSearchLimit cannot be called on $this->getConfig() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
229
        }
230
        $term = trim($term);
231
        if ($term == "" || !preg_match('/[^*]/', $term)) {
232
            return array();
233
        }
234
        // don't even try to search for empty prefix
235
236
        // make vocids an array in every case
237
        if ($vocids === null) {
238
            $vocids = array();
239
        }
240
241
        if (!is_array($vocids)) {
242
            $vocids = array($vocids);
243
        }
244
245
        $vocabs = array();
246
        foreach ($vocids as $vocid) {
247
            $vocabs[] = $this->getVocabulary($vocid);
248
        }
249
250 View Code Duplication
        if (sizeof($vocids) == 1) { // search within vocabulary
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
251
            $voc = $vocabs[0];
252
            $sparql = $voc->getSparql();
253
            $arrayClass = $voc->getConfig()->getArrayClassURI();
254
        } else { // multi-vocabulary or global search
255
            $voc = null;
256
            $arrayClass = null;
257
            $sparql = $this->getDefaultSparql();
258
        }
259
        if ($type === null) {
260
            $type = array('skos:Concept');
261
        }
262
263
        $results = $sparql->queryConcepts($term, $vocabs, $lang, $search_lang, $limit, $offset, $arrayClass, $type, $parent, $group, $hidden, $fields);
264
        $ret = array();
265
266
        foreach ($results as $hit) {
267
            if (sizeof($vocids) == 1) {
268
                $hit['vocab'] = $vocids[0];
269
            } else {
270
                try {
271
                    $voc = $this->getVocabularyByGraph($hit['graph']);
272
                    $hit['vocab'] = $voc->getId();
273
                } catch (Exception $e) {
274
                    trigger_error($e->getMessage(), E_USER_WARNING);
275
                    $voc = null;
276
                    $hit['vocab'] = "???";
277
                }
278
            }
279
            unset($hit['graph']);
280
281
            $hit['voc'] = $voc;
282
283
            // if uri is a external vocab uri that is included in the current vocab
284
            $realvoc = $this->guessVocabularyFromURI($hit['uri']);
285
            if ($realvoc != $voc) {
286
                unset($hit['localname']);
287
                $hit['exvocab'] = ($realvoc !== null) ? $realvoc->getId() : "???";
288
            }
289
290
            $ret[] = $hit;
291
        }
292
293
        return $ret;
294
    }
295
296
    /**
297
     * Function for performing a search for concepts and their data fields.
298
     * @param string $term searchterm eg. 'cat'
299
     * @param mixed $vocids vocabulary id eg. 'yso', array of such ids for multi-vocabulary search, or null for global search.
300
     * @param string $lang language code of returned labels, eg. 'fi'
301
     * @param string $search_lang language code used for matching, eg. 'fi', or null for anything
302
     * @param integer $offset used for offsetting the result set eg. '20'
303
     * @param integer $limit upper count for the search results eg. '10'
304
     * @param string $type limit search to concepts of the given type
305
     * @param string $parent limit search to concepts which have the given concept as parent in the transitive broader hierarchy
306
     * @param string $group limit search to concepts which are in the given group
307
     * @return array array with keys 'count' and 'results'
308
     */
309
    public function searchConceptsAndInfo($term, $vocids, $lang, $search_lang, $offset = 0, $limit = 20, $type = null, $parent = null, $group = null)
310
    {
311
        // make vocids an array in every case
312
        if ($vocids === null) {
313
            $vocids = array();
314
        }
315
316
        if (!is_array($vocids)) {
317
            $vocids = array($vocids);
318
        }
319
320
        $allhits = $this->searchConcepts($term, $vocids, $lang, $search_lang, $type, $parent, $group, 0, 0);
321
        $hits = array_slice($allhits, $offset, $limit);
322
323
        $uris = array();
324
        $vocabs = array();
325
        $uniqueVocabs = array();
326
        foreach ($hits as $hit) {
327
            $uniqueVocabs[$hit['voc']->getId()] = $hit['voc']->getId();
328
            $vocabs[] = $hit['voc'];
329
            $uris[] = $hit['uri'];
330
        }
331 View Code Duplication
        if (sizeof($uniqueVocabs) == 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
332
            $voc = $vocabs[0];
333
            $sparql = $voc->getSparql();
334
            $arrayClass = $voc->getConfig()->getArrayClassURI();
335
        } else {
336
            $arrayClass = null;
337
            $sparql = $this->getDefaultSparql();
338
        }
339
        $ret = $sparql->queryConceptInfo($uris, $arrayClass, $vocabs, null, $search_lang);
340
341
        // For marking that the concept has been found through an alternative label, hidden
342
        // label or a label in another language
343
        foreach ($hits as $idx => $hit) {
344
            if (isset($hit['altLabel']) && isset($ret[$idx])) {
345
                $ret[$idx]->setFoundBy($hit['altLabel'], 'alt');
346
            }
347
348
            if (isset($hit['hiddenLabel']) && isset($ret[$idx])) {
349
                $ret[$idx]->setFoundBy($hit['hiddenLabel'], 'hidden');
350
            }
351
352
            if (isset($hit['matchedPrefLabel'])) {
353
                $ret[$idx]->setFoundBy($hit['matchedPrefLabel'], 'lang');
354
            }
355
356
            if ($ret[$idx]) {
357
                $ret[$idx]->setContentLang($hit['lang']);
358
            }
359
360
        }
361
362
        return array('count' => sizeof($allhits), 'results' => $ret);
363
    }
364
365
    /**
366
     * Creates dataobjects from an input array.
367
     * @param string $class the type of class eg. 'Vocabulary'.
368
     * @param array $resarr contains the EasyRdf_Resources.
369
     */
370
    private function createDataObjects($class, $resarr)
371
    {
372
        $ret = array();
373
        foreach ($resarr as $res) {
374
            $ret[] = new $class($this, $res);
375
        }
376
377
        return $ret;
378
    }
379
380
    /**
381
     * Returns the cached vocabularies.
382
     * @return array of Vocabulary dataobjects
383
     */
384
    public function getVocabularies()
385
    {
386
        if ($this->all_vocabularies === null) { // initialize cache
387
            $vocs = $this->graph->allOfType('skosmos:Vocabulary');
388
            $this->all_vocabularies = $this->createDataObjects("Vocabulary", $vocs);
389
            foreach ($this->all_vocabularies as $voc) {
390
                // register vocabulary ids as RDF namespace prefixes
391
                $prefix = preg_replace('/\W+/', '', $voc->getId()); // strip non-word characters
392
                try {
393
                    if ($prefix != '' && EasyRdf_Namespace::get($prefix) === null) // if not already defined
394
                    {
395
                        EasyRdf_Namespace::set($prefix, $voc->getUriSpace());
396
                    }
397
398
                } catch (Exception $e) {
399
                    // not valid as namespace identifier, ignore
400
                }
401
            }
402
        }
403
404
        return $this->all_vocabularies;
405
    }
406
407
    /**
408
     * Returns the cached vocabularies from a category.
409
     * @param EasyRdf_Resource $cat the category in question
410
     * @return array of vocabulary dataobjects
411
     */
412
    public function getVocabulariesInCategory($cat)
413
    {
414
        $vocs = $this->graph->resourcesMatching('dc:subject', $cat);
415
416
        return $this->createDataObjects("Vocabulary", $vocs);
417
    }
418
419
    /**
420
     * Creates dataobjects of all the different vocabulary categories (Health etc.).
421
     * @return array of Dataobjects of the type VocabularyCategory.
422
     */
423
    public function getVocabularyCategories()
424
    {
425
        $cats = $this->graph->allOfType('skos:Concept');
426
427
        return $this->createDataObjects("VocabularyCategory", $cats);
428
    }
429
430
    /**
431
     * Returns the label defined in vocabularies.ttl with the appropriate language.
432
     * @param string $lang language code of returned labels, eg. 'fi'
433
     * @return string the label for vocabulary categories.
434
     */
435
    public function getClassificationLabel($lang)
436
    {
437
        $cats = $this->graph->allOfType('skos:ConceptScheme');
438
        $label = $cats ? $cats[0]->label($lang) : null;
439
440
        return $label;
441
    }
442
443
    /**
444
     * Returns a single cached vocabulary.
445
     * @param string $vocid the vocabulary id eg. 'mesh'.
446
     * @return vocabulary dataobject
447
     */
448
    public function getVocabulary($vocid)
449
    {
450
        $vocs = $this->getVocabularies();
451
        foreach ($vocs as $voc) {
452
            if ($voc->getId() == $vocid) {
453
                return $voc;
454
            }
455
        }
456
        throw new Exception("Vocabulary id '$vocid' not found in configuration.");
457
    }
458
459
    /**
460
     * Return the vocabulary that is stored in the given graph on the given endpoint.
461
     *
462
     * @param $graph string graph URI
463
     * @param $endpoint string endpoint URL (default SPARQL endpoint if omitted)
464
     * @return Vocabulary vocabulary of this URI, or null if not found
465
     */
466
    public function getVocabularyByGraph($graph, $endpoint = null)
467
    {
468
        if ($endpoint === null) {
469
            $endpoint = $this->getConfig()->getDefaultEndpoint();
0 ignored issues
show
Bug introduced by
The method getDefaultEndpoint cannot be called on $this->getConfig() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
470
        }
471
        if ($this->vocabs_by_graph === null) { // initialize cache
472
            $this->vocabs_by_graph = array();
473
            foreach ($this->getVocabularies() as $voc) {
474
                $key = json_encode(array($voc->getGraph(), $voc->getEndpoint()));
475
                $this->vocabs_by_graph[$key] = $voc;
476
            }
477
        }
478
479
        $key = json_encode(array($graph, $endpoint));
480
        if (array_key_exists($key, $this->vocabs_by_graph)) {
481
            return $this->vocabs_by_graph[$key];
482
        } else {
483
            throw new Exception("no vocabulary found for graph $graph and endpoint $endpoint");
484
        }
485
486
    }
487
488
    /**
489
     * Guess which vocabulary a URI originates from, based on the declared
490
     * vocabulary URI spaces.
491
     *
492
     * @param $uri string URI to search
493
     * @return Vocabulary vocabulary of this URI, or null if not found
494
     */
495
    public function guessVocabularyFromURI($uri)
496
    {
497
        if ($this->vocabs_by_urispace === null) { // initialize cache
498
            $this->vocabs_by_urispace = array();
499
            foreach ($this->getVocabularies() as $voc) {
500
                $this->vocabs_by_urispace[$voc->getUriSpace()] = $voc;
501
            }
502
        }
503
504
        // try to guess the URI space and look it up in the cache
505
        $res = new EasyRdf_Resource($uri);
506
        $namespace = substr($uri, 0, -strlen($res->localName()));
507
        if (array_key_exists($namespace, $this->vocabs_by_urispace)) {
508
            return $this->vocabs_by_urispace[$namespace];
509
        }
510
511
        // didn't work, try to match with each URI space separately
512
        foreach ($this->vocabs_by_urispace as $urispace => $voc) {
513
            if (strpos($uri, $urispace) === 0) {
514
                return $voc;
515
            }
516
        }
517
518
        // not found
519
        return null;
520
    }
521
522
    /**
523
     * Get the label for a resource, preferring 1. the given language 2. configured languages 3. any language.
524
     * @param EasyRdf_Resource $res resource whose label to return
525
     * @param string $lang preferred language
526
     * @return EasyRdf_Literal label as an EasyRdf_Literal object, or null if not found
527
     */
528
    public function getResourceLabel($res, $lang)
529
    {
530
        $langs = array_merge(array($lang), array_keys($this->config->getLanguages()));
0 ignored issues
show
Bug introduced by
The property config does not seem to exist. Did you mean global_config?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
531
        foreach ($langs as $l) {
532
            $label = $res->label($l);
533
            if ($label !== null) {
534
                return $label;
535
            }
536
537
        }
538
        return $res->label(); // desperate check for label in any language; will return null if even this fails
539
    }
540
541
    private function fetchResourceFromUri($uri)
542
    {
543
        try {
544
            // change the timeout setting for external requests
545
            $httpclient = EasyRdf_Http::getDefaultHttpClient();
546
            $httpclient->setConfig(array('timeout' => $this->getConfig()->getHttpTimeout()));
0 ignored issues
show
Bug introduced by
The method getHttpTimeout cannot be called on $this->getConfig() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
547
            EasyRdf_Http::setDefaultHttpClient($httpclient);
548
549
            $client = EasyRdf_Graph::newAndLoad(EasyRdf_Utils::removeFragmentFromUri($uri));
550
            return $client->resource($uri);
551
        } catch (Exception $e) {
552
            return null;
553
        }
554
    }
555
556
    public function getResourceFromUri($uri)
557
    {
558
        EasyRdf_Format::unregister('json'); // prevent parsing errors for sources which return invalid JSON
559
        // using apc cache for the resource if available
560
        if (function_exists('apc_store') && function_exists('apc_fetch')) {
561
            $key = 'fetch: ' . EasyRdf_Utils::removeFragmentFromUri($uri);
562
            $resource = apc_fetch($key);
563
            if ($resource === null || $resource === false) { // was not found in cache, or previous request failed
564
                $resource = $this->fetchResourceFromUri($uri);
565
                apc_store($key, $resource, $this->URI_FETCH_TTL);
566
            }
567
        } else { // APC not available, parse on every request
568
            $resource = $this->fetchResourceFromUri($uri);
569
        }
570
        return $resource;
571
    }
572
573
    /**
574
     * Returns a SPARQL endpoint object.
575
     * @param string $dialect eg. 'JenaText'.
576
     * @param string $endpoint url address of endpoint
577
     * @param string $graph uri for the target graph.
578
     */
579
    public function getSparqlImplementation($dialect, $endpoint, $graph)
580
    {
581
        $classname = $dialect . "Sparql";
582
583
        return new $classname($endpoint, $graph, $this);
584
    }
585
586
    /**
587
     * Returns a SPARQL endpoint object using the default implementation set in the config.inc.
588
     */
589
    public function getDefaultSparql()
590
    {
591
        return $this->getSparqlImplementation($this->getConfig()->getDefaultSparqlDialect(), $this->getConfig()->getDefaultEndpoint(), '?graph');
0 ignored issues
show
Bug introduced by
The method getDefaultSparqlDialect cannot be called on $this->getConfig() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
Bug introduced by
The method getDefaultEndpoint cannot be called on $this->getConfig() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
592
    }
593
594
}
595