VocabularyCache::setDocument()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 16
c 0
b 0
f 0
ccs 8
cts 8
cp 1
rs 9.7333
cc 3
nc 2
nop 2
crap 3
1
<?php
2
3
/**
4
 * micrometa
5
 *
6
 * @category   Jkphl
7
 * @package    Jkphl\Rdfalite
8
 * @subpackage Jkphl\Micrometa\Infrastructure
9
 * @author     Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright  Copyright © 2018 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license    http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2018 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Jkphl\Micrometa\Infrastructure\Parser\JsonLD;
38
39
use Jkphl\Micrometa\Ports\Cache;
40
use ML\JsonLD\RemoteDocument;
41
42
/**
43
 * Vocabulary cache
44
 *
45
 * @package    Jkphl\Rdfalite
46
 * @subpackage Jkphl\Micrometa\Infrastructure
47
 */
48
class VocabularyCache
49
{
50
    /**
51
     * Document cache slot
52
     *
53
     * @var string
54
     */
55
    const SLOT_DOC = 'jsonld.doc';
56
    /**
57
     * Vocabulary cache slot
58
     *
59
     * @var string
60
     */
61
    const SLOT_VOCABS = 'jsonld.vocabs';
62
    /**
63
     * Documents
64
     *
65
     * @var RemoteDocument[]
66
     */
67
    protected $documents = [];
68
    /**
69
     * Vocabularies
70
     *
71
     * @var array
72
     */
73
    protected $vocabularies = [];
74
    /**
75
     * Vocabulary prefices
76
     *
77
     * @var array
78
     */
79
    protected $prefices = [];
80
81
    /**
82
     * Return a cached document
83
     *
84
     * @param string $url URL
85
     *
86
     * @return RemoteDocument|null Cached document
87
     */
88 2
    public function getDocument($url)
89
    {
90 2
        $urlHash = $this->getCacheHash($url, self::SLOT_DOC);
91
92
        // Try to retrieve the document from the cache
93 2
        if (Cache::getAdapter()->hasItem($urlHash)) {
94 1
            return Cache::getAdapter()->getItem($urlHash)->get();
95
        }
96
97 2
        return null;
98
    }
99
100
    /**
101
     * Create a cache hash
102
     *
103
     * @param string $str  String
104
     * @param string $slot Slot
105
     *
106
     * @return string URL hash
107
     */
108 2
    protected function getCacheHash($str, $slot)
109
    {
110 2
        return $slot.'.'.md5($str);
111
    }
112
113
    /**
114
     * Cache a document
115
     *
116
     * @param string $url              URL
117
     * @param RemoteDocument $document Document
118
     *
119
     * @return RemoteDocument Document
120
     */
121 2
    public function setDocument($url, RemoteDocument $document)
122
    {
123
        // Process the context
124 2
        if (isset($document->document->{'@context'}) && is_object($document->document->{'@context'})) {
125 2
            $this->processContext((array)$document->document->{'@context'});
126
        }
127
128
        // Save the document to the cache
129 2
        $docUrlHash     = $this->getCacheHash($url, self::SLOT_DOC);
130 2
        $cachedDocument = Cache::getAdapter()->getItem($docUrlHash);
131 2
        $cachedDocument->set($document);
132 2
        Cache::getAdapter()->save($cachedDocument);
133
134
        // Return the document
135 2
        return $document;
136
    }
137
138
    /**
139
     * Process a context vocabulary
140
     *
141
     * @param array $context Context
142
     */
143 2
    protected function processContext(array $context)
144
    {
145 2
        $prefices        = [];
146 2
        $vocabularyCache = Cache::getAdapter()->getItem(self::SLOT_VOCABS);
147 2
        $vocabularies    = $vocabularyCache->isHit() ? $vocabularyCache->get() : [];
148
149
        // Run through all vocabulary terms
150 2
        foreach ($context as $name => $definition) {
151
            // Skip JSON-LD reserved terms
152 2
            if ($this->isReservedTokens($name, $definition)) {
153 2
                continue;
154
            }
155
156
            // Process this prefix / vocabulary term
157 2
            $this->processPrefixVocabularyTerm($name, $definition, $prefices, $vocabularies);
158
        }
159
160 2
        $vocabularyCache->set($vocabularies);
161 2
        Cache::getAdapter()->save($vocabularyCache);
162 2
    }
163
164
    /**
165
     * Test if a vocabulary name or definition is a reserved term
166
     *
167
     * @param string $name       Name
168
     * @param string $definition Definition
169
     *
170
     * @return boolean Is reserved term
171
     */
172 2
    protected function isReservedTokens($name, $definition)
173
    {
174 2
        return !strncmp('@', $name, 1) || (is_string($definition) && !strncmp('@', $definition, 1));
175
    }
176
177
    /**
178
     * Process a prefix / vocabulary term
179
     *
180
     * @param string $name                 Prefix name
181
     * @param string|\stdClass $definition Definition
182
     * @param array $prefices              Prefix register
183
     * @param array $vocabularies          Vocabulary register
184
     */
185 2
    protected function processPrefixVocabularyTerm($name, $definition, array &$prefices, array &$vocabularies)
186
    {
187
        // Register a prefix (and vocabulary)
188 2
        if ($this->isPrefix($name, $definition, $prefices)) {
189 2
            $this->processPrefix($name, strval($definition), $prefices, $vocabularies);
190
191
            // Else: Register vocabulary term
192 2
        } elseif ($this->isTerm($definition)) {
193 2
            $this->processVocabularyTerm((object)$definition, $prefices, $vocabularies);
194
        }
195 2
    }
196
197
    /**
198
     * Test whether this is a prefix and vocabulary definition
199
     *
200
     * @param string $name                 Prefix name
201
     * @param string|\stdClass $definition Definition
202
     * @param array $prefices              Prefix register
203
     *
204
     * @return bool Is a prefix and vocabulary definition
205
     */
206 2
    protected function isPrefix($name, $definition, array &$prefices)
207
    {
208 2
        return is_string($definition) && !isset($prefices[$name]);
209
    }
210
211
    /**
212
     * Process a vocabulary prefix
213
     *
214
     * @param string $name        Prefix name
215
     * @param string $definition  Prefix definition
216
     * @param array $prefices     Prefix register
217
     * @param array $vocabularies Vocabulary register
218
     */
219 2
    protected function processPrefix($name, $definition, array &$prefices, array &$vocabularies)
220
    {
221 2
        $prefices[$name] = $definition;
222
223
        // Register the vocabulary
224 2
        if (!isset($vocabularies[$definition])) {
225 1
            $vocabularies[$definition] = [];
226
        }
227 2
    }
228
229
    /**
230
     * Test whether this is a term definition
231
     *
232
     * @param string|\stdClass $definition Definition
233
     *
234
     * @return bool Is a term definition
235
     */
236 2
    protected function isTerm($definition)
237
    {
238 2
        return is_object($definition) && isset($definition->{'@id'});
239
    }
240
241
    /**
242
     * Process a vocabulary term
243
     *
244
     * @param \stdClass $definition Term definition
245
     * @param array $prefices       Prefix register
246
     * @param array $vocabularies   Vocabulary register
247
     */
248 2
    protected function processVocabularyTerm($definition, array &$prefices, array &$vocabularies)
249
    {
250 2
        $prefixName = explode(':', $definition->{'@id'}, 2);
251 2
        if (count($prefixName) == 2) {
252 2
            if (isset($prefices[$prefixName[0]])) {
253 2
                $vocabularies[$prefices[$prefixName[0]]][$prefixName[1]] = true;
254
            }
255
        }
256 2
    }
257
258
    /**
259
     * Create an IRI from a name considering the known vocabularies
260
     *
261
     * @param string $name Name
262
     *
263
     * @return \stdClass IRI
264
     */
265 4
    public function expandIRI($name)
266
    {
267 4
        $iri          = (object)['name' => $name, 'profile' => ''];
268 4
        $vocabularies = Cache::getAdapter()->getItem(self::SLOT_VOCABS);
269
270
        // Run through all vocabularies
271 4
        if ($vocabularies->isHit()) {
272 3
            $this->matchVocabularies($name, $vocabularies->get(), $iri);
273
        }
274
275 4
        return $iri;
276
    }
277
278
    /**
279
     * Match a name with the known vocabularies
280
     *
281
     * @param string $name        Name
282
     * @param array $vocabularies Vocabularies
283
     * @param \stdClass $iri      IRI
284
     */
285 3
    protected function matchVocabularies($name, array $vocabularies, &$iri)
286
    {
287
        // Run through all vocabularies
288 3
        foreach ($vocabularies as $profile => $terms) {
289 3
            $profileLength = strlen($profile);
290
291
            // If the name matches the profile and the remaining string is a registered term
292 3
            if (!strncasecmp($profile, $name, $profileLength) && !empty($terms[substr($name, $profileLength)])) {
293 2
                $iri->profile = $profile;
294 2
                $iri->name    = substr($name, $profileLength);
295
296 2
                return;
297
            }
298
        }
299 3
    }
300
}
301