Passed
Branch dev (be6874)
by Jakob
02:59
created

Parser::parse()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 41
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 23
nc 9
nop 4
dl 0
loc 41
rs 8.439
c 0
b 0
f 0
1
<?php declare(strict_types = 1);
2
3
namespace JSKOS\RDF;
4
5
use JSKOS\PrettyJsonSerializable;
6
use ML\JsonLD\JsonLD;
7
use ML\JsonLD\NQuads;
8
use ML\IRI\IRI;
9
use ML\JsonLD\LanguageTaggedString;
10
use EasyRdf_Graph;
11
12
/**
13
 * EasyRdf parser to support JSON-LD to RDF conversion.
14
 *
15
 * Bridges PHP packages EasyRDF and json-ld.
16
 */
17
class Parser extends \EasyRdf_Parser
18
{
19
    protected $context;
20
21
    /**
22
     * Parse JSKOS Resources to RDF.
23
     */
24
    public function parseJSKOS(PrettyJsonSerializable $jskos): EasyRdf_Graph
25
    {
26
        if (!$this->context) {
27
            $this->context = json_decode(file_get_contents(__DIR__.'/jskos-context.json'));
28
        }
29
        
30
        $data = $jskos->jsonLDSerialize('');        
31
        if (!count($data['type'] ?? [])) { # TODO: put into JSKOS core package?
32
            $class = get_class($jskos);
33
            $data['type'] = [ $class::TYPES[0] ];
34
        }
35
36
        $rdf = JsonLD::toRdf(json_encode($data), ['expandContext' => $this->context]);
37
        # TODO: catch (\ML\JsonLD\Exception\JsonLdException $e) 
38
39
        $graph = new EasyRdf_Graph();
40
        $this->parse($graph, $rdf);
41
42
	    return $graph;
43
    }
44
45
    /**
46
     * Parse Quads as returned by JsonLD.
47
     */
48
	public function parse($graph, $data, $format='jsonld', $baseUri=NULL) 
49
 	{
50
		parent::checkParseParams($graph, $data, $format, $baseUri);
51
52
		foreach ($data as $quad) {
53
		  $subject = (string) $quad->getSubject();
54
55
		  if ('_:' === substr($subject, 0, 2)) {
56
			$subject = $this->remapBnode($subject);
57
		  }
58
59
		  $predicate = (string) $quad->getProperty();
60
61
		  if ($quad->getObject() instanceof IRI) {
62
			$object = array(
63
			  'type' => 'uri',
64
			  'value' => (string) $quad->getObject()
65
			);
66
67
			if ('_:' === substr($object['value'], 0, 2)) {
68
			  $object = array(
69
				'type' => 'bnode',
70
				'value' => $this->remapBnode($object['value'])
71
			  );
72
			}
73
		  }
74
		  else {
75
			$object = array(
76
			  'type' => 'literal',
77
			  'value' => $quad->getObject()->getValue()
78
			);
79
80
			if ($quad->getObject() instanceof LanguageTaggedString) {
81
			  $object['lang'] = $quad->getObject()->getLanguage();
82
			}
83
			else {
84
			  $object['datatype'] = $quad->getObject()->getType();
85
			}
86
		  }
87
88
		  $this->addTriple($subject, $predicate, $object);
89
		}
90
    }
91
}
92