Completed
Pull Request — master (#1166)
by Osma
02:19
created

VocabularyConfig::getSparqlGraph()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * VocabularyConfig provides access to the vocabulary configuration defined in config.ttl.
5
 */
6
class VocabularyConfig extends BaseConfig
7
{
8
    private $plugins;
9
    private $pluginParameters;
10
    private $languageOrderCache = array();
11
12
    const DEFAULT_PROPERTY_ORDER = array("rdf:type", "dc:isReplacedBy",
13
    "skos:definition", "skos:broader", "isothes:broaderGeneric",
14
    "isothes:broaderPartitive", "isothes:broaderInstantial",
15
    "skos:narrower", "isothes:narrowerGeneric", "isothes:narrowerPartitive",
16
    "isothes:narrowerInstantial", "skos:related", "skos:altLabel",
17
    "skos:note", "skos:scopeNote", "skos:historyNote", "rdfs:comment",
18
    "dc11:source", "dc:source", "skosmos:memberOf", "skosmos:memberOfArray");
19
20
    const ISO25964_PROPERTY_ORDER = array("rdf:type", "dc:isReplacedBy",
21
    // ISO 25964 allows placing all text fields (inc. SN and DEF) together
22
    // so we will do that, except for HN, which is clearly administrative
23
    "skos:note", "skos:scopeNote", "skos:definition", "rdfs:comment",
24
    "dc11:source", "dc:source", "skos:altLabel", "skos:broader",
25
    "isothes:broaderGeneric", "isothes:broaderPartitive",
26
    "isothes:broaderInstantial", "skos:narrower", "isothes:narrowerGeneric",
27
    "isothes:narrowerPartitive", "isothes:narrowerInstantial",
28
    "skos:related", "skos:historyNote", "skosmos:memberOf",
29
    "skosmos:memberOfArray");
30
31
    public function __construct($resource, $globalPlugins=array())
32
    {
33
        $this->resource = $resource;
34
        $plugins = $this->resource->allLiterals('skosmos:usePlugin');
35
        $pluginArray = array();
36
        if ($plugins) {
37
            foreach ($plugins as $pluginlit) {
38
                $pluginArray[] = $pluginlit->getValue();
39
            }
40
        }
41
        $this->plugins = new PluginRegister(array_merge($globalPlugins, $pluginArray));
42
        // Get parameterized plugins defined as resources and their respective parameters
43
        $pluginResources = $this->resource->allResources('skosmos:useParamPlugin');
44
        $this->pluginParameters = array();
45
        if ($pluginResources) {
46
            foreach ($pluginResources as $pluginResource) {
47
                $pluginName = $pluginResource->getLiteral('skosmos:usePlugin')->getValue();
48
                $this->pluginParameters[$pluginName] = array();
49
50
                $pluginParams = $pluginResource->allResources('skosmos:parameters');
51
                foreach ($pluginParams as $parameter) {
52
53
                    $paramLiterals = $parameter->allLiterals('schema:value');
54
                    foreach ($paramLiterals as $paramLiteral) {
55
                        $paramName = $parameter->getLiteral('schema:propertyID')->getValue();
56
                        $paramValue = $paramLiteral->getValue();
57
                        $paramLang = $paramLiteral->getLang();
58
                        if ($paramLang) {
59
                            $paramName .= '_' . $paramLang;
60
                        }
61
                        $this->pluginParameters[$pluginName][$paramName] = $paramValue;
62
                    }
63
                }
64
                $pluginArray[] = $pluginName;
65
            }
66
            $this->plugins = new PluginRegister(array_merge($globalPlugins, $pluginArray));
67
        }
68
69
    }
70
71
    /**
72
     * Get the SPARQL endpoint URL for this vocabulary
73
     *
74
     * @return string|null endpoint URL, or null if not set
75
     */
76
    public function getSparqlEndpoint()
77
    {
78
        $endpoint = $this->resource->get('void:sparqlEndpoint');
79
        if ($endpoint) {
80
            return $endpoint->getUri();
81
        }
82
        return null;
83
    }
84
85
    /**
86
     * Get the SPARQL graph URI for this vocabulary
87
     *
88
     * @return string|null graph URI, or null if not set
89
     */
90
    public function getSparqlGraph()
91
    {
92
        $graph = $this->resource->get('skosmos:sparqlGraph');
93
        if ($graph) {
94
            $graph = $graph->getUri();
95
        }
96
97
        return $graph;
98
    }
99
100
    /**
101
     * Get the SPARQL dialect for this vocabulary
102
     *
103
     * @return string|null dialect name
104
     */
105
    public function getSparqlDialect()
106
    {
107
        $dialect = $this->resource->get('skosmos:sparqlDialect');
108
        if ($dialect) {
109
            $dialect = $dialect->getValue();
110
        }
111
112
        return $dialect;
113
    }
114
115
    /**
116
     * Get the default language of this vocabulary
117
     * @return string default language, e.g. 'en'
118
     */
119
120
    public function getDefaultLanguage()
121
    {
122
        $deflang = $this->resource->getLiteral('skosmos:defaultLanguage');
123
        if ($deflang) {
124
            return $deflang->getValue();
125
        }
126
127
        $langs = $this->getLanguages();
128
        $deflang = reset($langs); // picking the first one from the list with reset since the keys are not numeric
129
        if (sizeof($langs) > 1) {
130
            trigger_error("Default language for vocabulary '" . $this->getShortName() . "' unknown, choosing '$deflang'.", E_USER_WARNING);
131
        }
132
133
        return $deflang;
134
    }
135
136
    /**
137
     * Whether the alphabetical index is small enough to be shown all at once.
138
     * @return boolean true if all concepts can be shown at once.
139
     */
140
    public function getAlphabeticalFull()
141
    {
142
        return $this->getBoolean('skosmos:fullAlphabeticalIndex');
143
    }
144
145
    /**
146
     * Returns a short name for a vocabulary if configured. If that has not been set
147
     * using vocabId as a fallback.
148
     * @return string
149
     */
150
    public function getShortName()
151
    {
152
        $shortname = $this->getLiteral('skosmos:shortName');
153
        if ($shortname)
154
          return $shortname;
155
156
        // if no shortname exists fall back to the id
157
        return $this->getId();
158
    }
159
160
    /**
161
     * Get the vocabulary feedback e-mail address and return it.
162
     *
163
     * @return string e-mail address or null if not defined.
164
     */
165
    public function getFeedbackRecipient()
166
    {
167
        $email = $this->resource->get('skosmos:feedbackRecipient');
168
        return isset($email) ? $email->getValue() : null;
169
    }
170
171
    /**
172
     * Returns the human readable vocabulary title.
173
     * @return string the title of the vocabulary
174
     */
175
    public function getTitle($lang = null)
176
    {
177
        return $this->getLiteral('dc:title', false, $lang);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
178
    }
179
180
    /**
181
     * Returns a boolean value set in the config.ttl config.
182
     * @return boolean
183
     */
184
    public function sortByNotation()
185
    {
186
        return $this->getBoolean('skosmos:sortByNotation');
187
    }
188
189
    /**
190
     * Returns a boolean value set in the config.ttl config.
191
     * @return boolean
192
     */
193
    public function showChangeList()
194
    {
195
        return $this->getBoolean('skosmos:showChangeList');
196
    }
197
198
    /**
199
     * get the URLs from which the vocabulary data can be downloaded
200
     * @return array Array with MIME type as key, URL as value
201
     */
202
    public function getDataURLs()
203
    {
204
        $ret = array();
205
        $urls = $this->resource->allResources("void:dataDump");
206
        foreach ($urls as $url) {
207
            // first try dc:format and dc11:format
208
            $mimetypelit = $url->getLiteral('dc:format');
209
            if ($mimetypelit === null) {
210
                $mimetypelit = $url->getLiteral('dc11:format');
211
            }
212
213
            if ($mimetypelit !== null) {
214
                $mimetype = $mimetypelit->getValue();
215
            } else {
216
                $format = EasyRdf\Format::guessFormat(null, $url->getURI());
217
                if ($format === null) {
218
                    trigger_error("Could not guess format for <$url>.", E_USER_WARNING);
219
                    continue;
220
                }
221
                $mimetypes = array_keys($format->getMimeTypes());
222
                $mimetype = $mimetypes[0];
223
            }
224
225
            $langLit = $url->getLiteral('dc:language');
226
227
            if ($langLit != null) {
228
                //when the mimetype has language variants
229
                $dataUrlLang = $langLit->getValue();
230
231
                if (!isset($ret[$mimetype])) {
232
                  $arr = array();
233
                } else {
234
                  $arr = $ret[$mimetype];
235
                }
236
                $arr[$dataUrlLang] = $url->getURI();
237
                $ret[$mimetype] = $arr;
238
            } else {
239
                $ret[$mimetype] = $url->getURI();
240
            }
241
        }
242
        return $ret;
243
    }
244
245
    /**
246
     * Returns the main Concept Scheme URI of that Vocabulary,
247
     * or null if not set.
248
     * @return string concept scheme URI or null
249
     */
250
251
    public function getMainConceptSchemeURI()
252
    {
253
        $val = $this->resource->getResource("skosmos:mainConceptScheme");
254
        if ($val) {
255
            return $val->getURI();
256
        }
257
258
        return null;
259
    }
260
261
    /**
262
     * Returns the class URI used for concept groups in this vocabulary,
263
     * or null if not set.
264
     * @return string group class URI or null
265
     */
266
267
    public function getGroupClassURI()
268
    {
269
        $val = $this->resource->getResource("skosmos:groupClass");
270
        if ($val) {
271
            return $val->getURI();
272
        }
273
274
        return null;
275
    }
276
277
    /**
278
     * Returns the class URI used for thesaurus arrays in this vocabulary,
279
     * or null if not set.
280
     * @return string array class URI or null
281
     */
282
283
    public function getArrayClassURI()
284
    {
285
        $val = $this->resource->getResource("skosmos:arrayClass");
286
        if ($val) {
287
            return $val->getURI();
288
        }
289
290
        return null;
291
    }
292
293
    /**
294
     * Returns custom properties displayed on the search page if configured.
295
     * @return array array class URI or null
296
     */
297
298 View Code Duplication
    public function getAdditionalSearchProperties()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
299
    {
300
        $resources = $this->resource->allResources("skosmos:showPropertyInSearch");
301
        $ret = array();
302
        foreach ($resources as $res) {
303
            $prop = $res->getURI();
304
            if (EasyRdf\RdfNamespace::shorten($prop) !== null) // shortening property labels if possible
305
            {
306
                $prop = EasyRdf\RdfNamespace::shorten($prop);
307
            }
308
309
            $ret[] = $prop;
310
        }
311
        return $ret;
312
    }
313
314
    /**
315
     * Queries whether the property should be shown with all the label language variations.
316
     * @param string $property
317
     * @return boolean
318
     */
319
    public function hasMultiLingualProperty($property)
320
    {
321
        $resources = $this->resource->allResources("skosmos:hasMultiLingualProperty");
322
        foreach ($resources as $res) {
323
            $prop = $res->getURI();
324
            if (EasyRdf\RdfNamespace::shorten($prop) !== null) // shortening property labels if possible
325
            {
326
                $prop = EasyRdf\RdfNamespace::shorten($prop);
327
            }
328
329
            if ($prop === $property) {
330
                return true;
331
            }
332
333
        }
334
        return false;
335
    }
336
337
    /**
338
     * Returns a boolean value set in the config.ttl config.
339
     * @return boolean
340
     */
341
    public function getShowHierarchy()
342
    {
343
        return $this->getBoolean('skosmos:showTopConcepts');
344
    }
345
346
    /**
347
     * Returns a boolean value set in the config.ttl config.
348
     * @return boolean
349
     */
350
    public function showConceptSchemesInHierarchy()
351
    {
352
        return $this->getBoolean('skosmos:conceptSchemesInHierarchy');
353
    }
354
355
    /**
356
     * Returns a boolean value set in the config.ttl config.
357
     * @return boolean defaults to true if fetching hasn't been explicitly denied.
358
     */
359
    public function getExternalResourcesLoading()
360
    {
361
        return $this->getBoolean('skosmos:loadExternalResources', true);
362
    }
363
364
    /**
365
     * Returns a boolean value set in the config.ttl config.
366
     * @return boolean
367
     */
368
    public function getShowLangCodes()
369
    {
370
        return $this->getBoolean('skosmos:explicitLanguageTags');
371
    }
372
373
    /**
374
     * Returns a boolean value set in the config.ttl config.
375
     * @return boolean
376
     */
377
    public function searchByNotation()
378
    {
379
        return $this->getBoolean('skosmos:searchByNotation');
380
    }
381
382
    /**
383
     * Returns skosmos:marcSourcecode value set in config.ttl.
384
     * @return string marcsource name
385
     */
386
    public function getMarcSourceCode($lang = null)
387
    {
388
        return $this->getLiteral('skosmos:marcSourceCode', false, $lang);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
389
    }
390
391
    /**
392
     * Returns a boolean value set in the config.ttl config.
393
     * @return array array of concept class URIs (can be empty)
394
     */
395
    public function getIndexClasses()
396
    {
397
        return $this->getResources("skosmos:indexShowClass");
398
    }
399
400
    /**
401
     * Returns skosmos:externalProperty values set in the config.ttl config.
402
     * @return array array of external property URIs (can be empty)
403
     */
404
    public function getExtProperties()
405
    {
406
        return $this->getResources("skosmos:externalProperty");
407
    }
408
409
    /**
410
     * Get the languages supported by this vocabulary
411
     * @return array languages supported by this vocabulary (as language tag strings)
412
     */
413
    public function getLanguages()
414
    {
415
        $langs = $this->resource->allLiterals('skosmos:language');
416
        $ret = array();
417
        foreach ($langs as $lang) {
418
            $langlit = Punic\Language::getName($lang->getValue(), $this->getEnvLang());
419
            $ret[$langlit] = $lang->getValue();
420
        }
421
        ksort($ret);
422
423
        return $ret;
424
    }
425
426
    /**
427
     * Returns the plugin parameters
428
     * @return string plugin parameters or null
429
     */
430
    public function getPluginParameters() {
431
        return json_encode($this->pluginParameters, true);
432
    }
433
434
    /**
435
     * Returns the vocabulary default sidebar view.
436
     * @return string name of the view
437
     */
438
    public function getDefaultSidebarView()
439
    {
440
        $defview = $this->resource->getLiteral('skosmos:defaultSidebarView');
441
        if ($defview) {
442
            $value = $defview->getValue();
443
            if ($value === 'groups' || $value === 'hierarchy') {
444
                return $value;
445
            }
446
447
        }
448
        if ($this->showAlphabeticalIndex() === false) {
449
            if ($this->getShowHierarchy()) {
450
                return 'hierarchy';
451
            } else if ($this->getGroupClassURI()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getGroupClassURI() of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
452
                return 'groups';
453
            }
454
        }
455
        return 'alphabetical'; // if not defined displaying the alphabetical index
456
    }
457
458
    /**
459
     * Extracts the vocabulary id string from the baseuri of the vocabulary.
460
     * @return string identifier eg. 'mesh'.
461
     */
462
    public function getId()
463
    {
464
        $uriparts = explode("#", $this->resource->getURI());
465
        if (count($uriparts) != 1)
466
        // hash namespace
467
        {
468
            return $uriparts[1];
469
        }
470
471
        // slash namespace
472
        $uriparts = explode("/", $this->resource->getURI());
473
474
        return $uriparts[count($uriparts) - 1];
475
    }
476
477
    public function getShowStatistics() {
478
        return $this->getBoolean('skosmos:showStatistics', true);
479
    }
480
481
    public function getPlugins()
482
    {
483
        return $this->plugins;
484
    }
485
486
    /**
487
     * Returns the property/properties used for visualizing concept hierarchies.
488
     * @return array array class URI or null
489
     */
490
491 View Code Duplication
    public function getHierarchyProperty()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
492
    {
493
        $resources = $this->resource->allResources("skosmos:hierarchyProperty");
494
        $ret = array();
495
        foreach ($resources as $res) {
496
            $prop = $res->getURI();
497
            if (EasyRdf\RdfNamespace::shorten($prop) !== null) // prefixing if possible
498
            {
499
                $prop = EasyRdf\RdfNamespace::shorten($prop);
500
            }
501
502
            $ret[] = $prop;
503
        }
504
        return empty($ret) ? array('skos:broader') : $ret;
505
    }
506
507
    /**
508
     * Returns a boolean value set in the config.ttl config.
509
     * @return boolean
510
     */
511
    public function showNotation()
512
    {
513
        return $this->getBoolean('skosmos:showNotation', true);
514
    }
515
516
    /**
517
     * Returns a boolean value set in the config.ttl config.
518
     * @return boolean
519
     */
520
    public function showAlphabeticalIndex()
521
    {
522
        return $this->getBoolean('skosmos:showAlphabeticalIndex', true);
523
    }
524
525
    /**
526
     * Returns the alphabetical list qualifier in this vocabulary,
527
     * or null if not set.
528
     * @return EasyRdf\Resource|null alphabetical list qualifier resource or null
529
     */
530
    public function getAlphabeticalListQualifier()
531
    {
532
        return $this->resource->getResource('skosmos:alphabeticalListQualifier');
533
    }
534
535
    /**
536
     * Returns a boolean value set in the config.ttl config.
537
     * @return boolean
538
     */
539
    public function getShowDeprecated()
540
    {
541
        return $this->getBoolean('skosmos:showDeprecated', false);
542
    }
543
544
    /**
545
     * Returns the vocabulary dc:type value(s) with their labels and uris, if set in the vocabulary configuration.
546
     * @return array of objects or an empty array
547
     */
548
    public function getTypes($lang = null)
549
    {
550
        $resources = $this->resource->allResources("dc:type");
551
        $ret = array();
552
        foreach ($resources as $res) {
553
            $prop = $res->getURI();
554
            $label = $res->label($lang) ? $res->label($lang) : $res->label($this->getDefaultLanguage());
555
            $ret[] = array('uri' => $prop, 'prefLabel' =>  $label->getValue());
556
        }
557
        return $ret;
558
    }
559
560
    /**
561
     * Returns an array of fallback languages that is ordered by priority and
562
     * defined in the vocabulary configuration as a collection.
563
     * Additionally, the chosen content language is inserted with the highest priority
564
     * and the vocab default language is inserted with the lowest priority.
565
     * @param string $clang
566
     * @return array of language code strings
567
     */
568
    public function getLanguageOrder($clang)
569
    {
570
        if (array_key_exists($clang, $this->languageOrderCache)) {
571
            return $this->languageOrderCache[$clang];
572
        }
573
        $ret = array($clang);
574
        $fallbacks = !empty($this->resource->get('skosmos:fallbackLanguages')) ? $this->resource->get('skosmos:fallbackLanguages') : array();
575
        foreach ($fallbacks as $lang) {
576
            if (!in_array($lang, $ret)) {
577
                $ret[] = (string)$lang; // Literal to string conversion
578
            }
579
        }
580
        if (!in_array($this->getDefaultLanguage(), $ret)) {
581
            $ret[] = (string)$this->getDefaultLanguage();
582
        }
583
        foreach ($this->getLanguages() as $lang) {
584
            if (!in_array($lang, $ret)) {
585
                $ret[] = $lang;
586
            }
587
        }
588
        // store in cache so this doesn't have to be computed again
589
        $this->languageOrderCache[$clang] = $ret;
590
        return $ret;
591
    }
592
593
    /**
594
     * @return boolean
595
     */
596
    public function isUseModifiedDate()
597
    {
598
        return $this->getBoolean('skosmos:useModifiedDate', false);
599
    }
600
601
    /**
602
     * @return array
603
     */
604
    public function getPropertyOrder()
605
    {
606
        $order = $this->getResource()->getResource('skosmos:propertyOrder');
607
        if ($order === null) {
608
            return self::DEFAULT_PROPERTY_ORDER;
609
        }
610
611
        $short = EasyRdf\RdfNamespace::shorten($order);
612
        if ($short == 'skosmos:iso25964PropertyOrder') {
613
            return self::ISO25964_PROPERTY_ORDER;
614
        } elseif ($short == 'skosmos:defaultPropertyOrder') {
615
            return self::DEFAULT_PROPERTY_ORDER;
616
        }
617
        
618
        // check for custom order definition
619
        $orderList = $order->getResource('rdf:value');
620
        if ($orderList !== null && $orderList instanceof EasyRdf\Collection) {
621
            $ret = array();
622
            foreach ($orderList as $prop) {
623
                $short = $prop->shorten();
624
                $ret[] = ($short !== null) ? $short : $prop->getURI();
625
            }
626
            return $ret;
627
        }
628
        
629
        trigger_error("Property order for vocabulary '{$this->getShortName()}' unknown, using default order", E_USER_WARNING);
630
        return self::DEFAULT_PROPERTY_ORDER;
631
    }
632
}
633