Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
67.50% covered (warning)
67.50%
54 / 80
37.50% covered (danger)
37.50%
6 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
JsonLdExport
67.50% covered (warning)
67.50%
54 / 80
37.50% covered (danger)
37.50%
6 / 16
84.00
0.00% covered (danger)
0.00%
0 / 1
 __construct
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 setResource
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 setTriples
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setTypes
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setUri
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 blackList
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 registerEncoder
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getEncoders
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 addTripleEncoder
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 jsonSerialize
70.97% covered (warning)
70.97%
22 / 31
0.00% covered (danger)
0.00%
0 / 1
12.45
 getBlackList
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 encodeValue
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
4.25
 generateId
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 applyEncoder
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
3.33
 encodeTriples
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 encodeValues
33.33% covered (danger)
33.33%
2 / 6
0.00% covered (danger)
0.00%
0 / 1
5.67
1<?php
2
3/**
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; under version 2
7 * of the License (non-upgradable).
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17 *
18 * Copyright (c) 2015-2021 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
19 */
20
21namespace oat\tao\model\export;
22
23use core_kernel_classes_Class;
24use core_kernel_classes_ContainerCollection;
25use core_kernel_classes_Property;
26use core_kernel_classes_Resource;
27use core_kernel_classes_Triple;
28use JsonSerializable;
29use oat\generis\model\data\Ontology;
30use oat\generis\model\OntologyRdf;
31use oat\tao\model\export\Metadata\JsonLd\JsonLdTripleEncoderInterface;
32
33/**
34 * A custom Json LD exporter for single resources
35 * that generates easily readable Json
36 *
37 * @access public
38 * @author Joel Bout, <joel@taotesting.com>
39 * @package tao
40 */
41class JsonLdExport implements JsonSerializable
42{
43    /** @var core_kernel_classes_ContainerCollection */
44    private $triples;
45
46    /** @var Ontology|null */
47    private $ontology;
48
49    /** @var core_kernel_classes_Class[] */
50    private $types;
51
52    /** @var string */
53    private $uri;
54
55    /** @var array */
56    private $blackList = [
57        OntologyRdf::RDF_TYPE
58    ];
59
60    /** @var array */
61    private $encoders = [];
62
63    /** @var JsonLdTripleEncoderInterface[] */
64    private $tripleEncoders = [];
65
66    /**
67     * @deprecated Do not use $resource in the constructor, use setResource instead.
68     *             This class is now instantiated in the DI container.
69     */
70    public function __construct(core_kernel_classes_Resource $resource = null, Ontology $ontology = null)
71    {
72        if (!is_null($resource)) {
73            $this->setResource($resource);
74        }
75
76        $this->ontology = $ontology;
77    }
78
79    public function setResource(core_kernel_classes_Resource $resource): self
80    {
81        $this->setTriples($resource->getRdfTriples());
82        $this->setTypes($resource->getTypes());
83        $this->setUri($resource->getUri());
84
85        return $this;
86    }
87
88    public function setTriples(core_kernel_classes_ContainerCollection $triples): self
89    {
90        $this->triples = $triples;
91
92        return $this;
93    }
94
95    /**
96     * @param array $types
97     */
98    public function setTypes($types): self
99    {
100        $this->types = $types;
101
102        return $this;
103    }
104
105    public function setUri(string $uri): self
106    {
107        $this->uri = $uri;
108
109        return $this;
110    }
111
112    public function blackList(string $propertyUri): void
113    {
114        $this->blackList[] = $propertyUri;
115    }
116
117    public function registerEncoder($propertyUri, callable $encoder): void
118    {
119        $this->encoders[$propertyUri] = $encoder;
120    }
121
122    public function getEncoders(): array
123    {
124        return $this->encoders;
125    }
126
127    public function addTripleEncoder(JsonLdTripleEncoderInterface $encoder): self
128    {
129        $this->tripleEncoders[get_class($encoder)] = $encoder;
130
131        return $this;
132    }
133
134    public function jsonSerialize(): array
135    {
136        $data = [
137            '@context' => [],
138            '@id' => $this->uri,
139        ];
140
141        if (!empty($this->types)) {
142            $data['@type'] = $this->encodeValues($this->types);
143        }
144
145        if (!$this->triples instanceof core_kernel_classes_ContainerCollection) {
146            return $data;
147        }
148
149        /** @var core_kernel_classes_Triple[] $triples */
150        $triples = $this->triples->toArray();
151        $map = [];
152
153        foreach ($triples as $key => $triple) {
154            if (in_array($triple->predicate, $this->blackList)) {
155                continue;
156            }
157
158            if (!isset($map[$triple->predicate])) {
159                $id = $this->generateId($triple->predicate);
160                if (in_array($id, $map)) {
161                    $nr = 0;
162                    while (in_array($id . '_' . $nr, $map)) {
163                        $nr++;
164                    }
165                    $id = $id . '_' . $nr;
166                }
167                $map[$triple->predicate] = $id;
168                $data['@context'][$id] = $triple->predicate;
169            }
170
171            $key = $map[$triple->predicate];
172            if (isset($data[$key])) {
173                if (!is_array($data[$key])) {
174                    $data[$key] = [$data[$key]];
175                }
176                $data[$key][] = $this->encodeValue($triple->object, $triple->predicate);
177            } else {
178                $data[$key] = $this->encodeValue($triple->object, $triple->predicate);
179            }
180        }
181
182        $data = $this->encodeTriples($data, ...$triples);
183
184        // Enforce serialization to object if context is empty
185        $data['@context'] = (object) $data['@context'];
186
187        return $data;
188    }
189
190    /**
191     * Gets a list of properties to exclude
192     *
193     * @return array()
194     */
195    protected function getBlackList()
196    {
197        return $this->blackList;
198    }
199
200    /**
201     * Encode the value in a json-ld compatible way
202     *
203     * @param mixed $value
204     * @param string $propertyUri (optional) The URI of the property the $value is related to.
205     * @return string
206     */
207    protected function encodeValue($value, $propertyUri = '')
208    {
209        $value = $this->applyEncoder($value, $propertyUri);
210
211        return is_string($value)
212            ? $value
213            : (
214                (is_object($value) && $value instanceof \core_kernel_classes_Resource)
215                ? $value->getUri()
216                : (string) $value
217            );
218    }
219
220    /**
221     * Generate a key for the property to use during export
222     *
223     * @param string $uri
224     * @return string
225     */
226    protected function generateId($uri)
227    {
228        $property = $this->ontology
229            ? $this->ontology->getProperty($uri)
230            : new core_kernel_classes_Property($uri);
231
232        $label = strtolower(trim($property->getLabel()));
233        $label = preg_replace(['/\s/', '[^a-z\-]'], ['-', ''], $label);
234
235        return empty($label) ? 'key' : $label;
236    }
237
238    /**
239     * Attempt to apply a specific value encoder.
240     *
241     * @param mixed $value
242     * @param string (optional) The URI of the property the $value belongs to.
243     * @return mixed
244     */
245    protected function applyEncoder($value, $propertyUri = '')
246    {
247        if (empty($propertyUri) === false) {
248            $encoders = $this->getEncoders();
249
250            if (isset($encoders[$propertyUri]) === true) {
251                $encodedValue = call_user_func($encoders[$propertyUri], $value);
252                return $encodedValue;
253            }
254        }
255
256        return $value;
257    }
258
259    private function encodeTriples(array $data, core_kernel_classes_Triple ...$triples): array
260    {
261        foreach ($this->tripleEncoders as $tripleEncoder) {
262            foreach ($triples as $triple) {
263                $data = $tripleEncoder->encode($data, $triple);
264            }
265        }
266
267        return $data;
268    }
269
270    /**
271     * @return string|array
272     */
273    private function encodeValues(array $values)
274    {
275        if (count($values) > 1) {
276            $encoded = [];
277
278            foreach ($values as $value) {
279                $encoded[] = $this->encodeValue($value);
280            }
281
282            return $encoded;
283        }
284
285        return $this->encodeValue(reset($values));
286    }
287}