Completed
Push — master ( aaa1df...c1536f )
by Richard van
13s queued 10s
created

JsonLD   A

Complexity

Total Complexity 39

Size/Duplication

Total Lines 327
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 97.98%

Importance

Changes 0
Metric Value
wmc 39
lcom 1
cbo 9
dl 0
loc 327
ccs 97
cts 99
cp 0.9798
rs 9.28
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A parseDom() 0 19 2
A parseDocument() 0 20 4
A parseRootNode() 0 19 3
A parseNode() 0 20 3
A parseNodeType() 0 18 4
A parseNodeProperties() 0 20 3
A initializeNodeProperty() 0 7 2
A processNodeProperty() 0 17 5
A processNodePropertyObject() 0 10 4
A parse() 0 18 4
A parseLanguageTaggedString() 0 4 1
A parseTypedValue() 0 4 1
A sanitizeJsonSource() 0 10 2
1
<?php
2
3
/**
4
 * micrometa
5
 *
6
 * @category   Jkphl
7
 * @package    Jkphl\Micrometa
8
 * @subpackage Jkphl\Micrometa\Infrastructure\Parser
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;
38
39
use Jkphl\Micrometa\Application\Contract\ParsingResultInterface;
40
use Jkphl\Micrometa\Infrastructure\Parser\JsonLD\CachingContextLoader;
41
use Jkphl\Micrometa\Infrastructure\Parser\JsonLD\VocabularyCache;
42
use Jkphl\Micrometa\Ports\Format;
43
use ML\JsonLD\Exception\JsonLdException;
44
use ML\JsonLD\JsonLD as JsonLDParser;
45
use ML\JsonLD\LanguageTaggedString;
46
use ML\JsonLD\Node;
47
use ML\JsonLD\NodeInterface;
48
use ML\JsonLD\TypedValue;
49
use Psr\Http\Message\UriInterface;
50
use Psr\Log\LoggerInterface;
51
52
/**
53
 * JsonLD parser
54
 *
55
 * @package    Jkphl\Micrometa
56
 * @subpackage Jkphl\Micrometa\Infrastructure
57
 * @see        https://jsonld-examples.com/
58
 * @see        http://www.dr-chuck.com/csev-blog/2016/04/json-ld-performance-sucks-for-api-specs/
59
 */
60
class JsonLD extends AbstractParser
61
{
62
    /**
63
     * Format
64
     *
65
     * @var int
66
     */
67
    const FORMAT = Format::JSON_LD;
68
    /**
69
     * Regex pattern for matching leading comments in a JSON string
70
     *
71
     * @var string
72
     */
73
    const JSON_COMMENT_PATTERN = '#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#';
74
    /**
75
     * Vocabulary cache
76
     *
77
     * @var VocabularyCache
78
     */
79
    protected $vocabularyCache;
80
    /**
81
     * Context loader
82
     *
83
     * @var CachingContextLoader
84
     */
85
    protected $contextLoader;
86
    /**
87
     * Array for keeping track of the hierarchy of objects, to prevent recursion
88
     *
89
     * @var NodeInterface[]
90
     */
91
    protected $chain = [];
92
93
    /**
94
     * JSON-LD parser constructor
95
     *
96
     * @param UriInterface $uri       Base URI
97
     * @param LoggerInterface $logger Logger
98
     */
99 8
    public function __construct(UriInterface $uri, LoggerInterface $logger)
100
    {
101 8
        parent::__construct($uri, $logger);
102 8
        $this->vocabularyCache = new VocabularyCache();
103 8
        $this->contextLoader   = new CachingContextLoader($this->vocabularyCache);
104 8
    }
105
106
    /**
107
     * Parse a DOM document
108
     *
109
     * @param \DOMDocument $dom DOM Document
110
     *
111
     * @return ParsingResultInterface Micro information items
112
     * @throws \ReflectionException
113
     */
114 7
    public function parseDom(\DOMDocument $dom)
115
    {
116 7
        $this->logger->info('Running parser: '.(new \ReflectionClass(__CLASS__))->getShortName());
117 7
        $items = [];
118
119
        // Find and process all JSON-LD documents
120 7
        $xpath      = new \DOMXPath($dom);
121 7
        $jsonLDDocs = $xpath->query('//*[local-name(.) = "script"][@type = "application/ld+json"]');
122 7
        $this->logger->debug('Processing '.$jsonLDDocs->length.' JSON-LD documents');
123
124
        // Run through all JSON-LD documents
125 7
        foreach ($jsonLDDocs as $jsonLDDoc) {
126 7
            $jsonLDDocSource = preg_replace(self::JSON_COMMENT_PATTERN, '', $jsonLDDoc->textContent);
127 7
            $i               = $this->parseDocument($jsonLDDocSource);
128 6
            $items           = array_merge($items, $i);
129
        }
130
131 6
        return new ParsingResult(self::FORMAT, $items);
132
    }
133
134
    /**
135
     * Parse a JSON-LD document
136
     *
137
     * @param string $jsonLDDocSource JSON-LD document
138
     *
139
     * @return array Items
140
     */
141 7
    protected function parseDocument($jsonLDDocSource)
142
    {
143 7
        $jsonLDDocSource = $this->sanitizeJsonSource($jsonLDDocSource);
144
145
        // Unserialize the JSON-LD document
146 7
        $jsonLDDoc = @json_decode($jsonLDDocSource);
147
148
        // If this is not a valid JSON document: Return
149 7
        if (!is_object($jsonLDDoc) && !is_array($jsonLDDoc)) {
150 3
            $this->logger->error('Skipping invalid JSON-LD document');
151
152 2
            return [];
153
        }
154
155
        // Parse the document
156 5
        return array_filter(
157 5
            is_array($jsonLDDoc) ?
158 5
                array_map([$this, 'parseRootNode'], $jsonLDDoc) : [$this->parseRootNode($jsonLDDoc)]
159
        );
160
    }
161
162
    /**
163
     * Parse a JSON-LD root node
164
     *
165
     * @param \stdClass $jsonLDRoot JSON-LD root node
166
     */
167 5
    protected function parseRootNode($jsonLDRoot)
168
    {
169 5
        $item = null;
170
171
        try {
172 5
            $jsonDLDocument = JsonLDParser::getDocument($jsonLDRoot, ['documentLoader' => $this->contextLoader]);
173
174
            // Run through all nodes to parse the first one
175
            /** @var Node $node */
176 5
            foreach ($jsonDLDocument->getGraph()->getNodes() as $node) {
177 5
                $item = $this->parseNode($node);
178 5
                break;
179
            }
180
        } catch (JsonLdException $exception) {
181
            $this->logger->error($exception->getMessage(), ['exception' => $exception]);
182
        }
183
184 5
        return $item;
185
    }
186
187
    /**
188
     * Parse a JSON-LD node
189
     *
190
     * @param NodeInterface $node Node
191
     *
192
     * @return \stdClass|string Item or string ID
193
     */
194 5
    protected function parseNode(NodeInterface $node)
195
    {
196 5
        $nodeId = $node->getId() ?: null;
197
198
        // if ID is in the current chain, just return the ID reference
199 5
        if (in_array($node, $this->chain, true)) {
200 1
            return $nodeId;
201
        }
202
203
        // add node to chain, parse node tree, remove node from chain
204 5
        $this->chain[] = $node;
205 5
        $properties = $this->parseNodeProperties($node);
206 5
        array_pop($this->chain);
207
208
        return (object)[
209 5
            'type'       => $this->parseNodeType($node),
210 5
            'id'         => $nodeId,
211 5
            'properties' => $properties,
212
        ];
213
    }
214
215
    /**
216
     * Parse the type of a JSON-LD node
217
     *
218
     * @param NodeInterface $node Node
219
     *
220
     * @return array Item type
221
     */
222 5
    protected function parseNodeType(NodeInterface $node): array
223
    {
224
        /** @var NodeInterface|NodeInterface[] $itemTypes */
225 5
        $itemTypes = $node->getType();
226 5
        $itemTypes = is_array($itemTypes) ? $itemTypes : [$itemTypes];
227 5
        $itemTypes = array_filter($itemTypes);
228
229 5
        if (empty($itemTypes)) {
230 3
            return [];
231
        }
232
233 5
        $types = [];
234 5
        foreach ($itemTypes as $itemType) {
235 5
            $types[] = $this->vocabularyCache->expandIRI($itemType->getId());
236
        }
237
238 5
        return $types;
239
    }
240
241
    /**
242
     * Parse the properties of a JSON-LD node
243
     *
244
     * @param NodeInterface $node Node
245
     *
246
     * @return array Item properties
247
     */
248 5
    protected function parseNodeProperties(NodeInterface $node)
249
    {
250 5
        $properties = [];
251
252
        // Run through all node properties
253 5
        foreach ($node->getProperties() as $name => $property) {
254
            // Skip the node type
255 5
            if ($name === Node::TYPE) {
256 5
                continue;
257
            }
258
259
            // Initialize the property (if necessary)
260 4
            $this->initializeNodeProperty($name, $properties);
261
262
            // Parse and process the property value
263 4
            $this->processNodeProperty($name, $this->parse($property), $properties);
264
        }
265
266 5
        return $properties;
267
    }
268
269
    /**
270
     * Initialize a JSON-LD node property (if necessary)
271
     *
272
     * @param string $name      Property name
273
     * @param array $properties Item properties
274
     */
275 4
    protected function initializeNodeProperty($name, array &$properties)
276
    {
277 4
        if (empty($properties[$name])) {
278 4
            $properties[$name]         = $this->vocabularyCache->expandIRI($name);
279 4
            $properties[$name]->values = [];
280
        }
281 4
    }
282
283
    /**
284
     * Process a property value
285
     *
286
     * @param string $name                  Property name
287
     * @param \stdClass|array|string $value Property value
288
     * @param array $properties             Item properties
289
     */
290 4
    protected function processNodeProperty($name, $value, array &$properties)
291
    {
292
        // If this is a nested item
293 4
        if (is_object($value)) {
294 3
            $this->processNodePropertyObject($name, $value, $properties);
295
296
            // Else: If this is a value list
297 4
        } elseif (is_array($value)) {
298 2
            foreach ($value as $listValue) {
299 2
                $this->processNodeProperty($name, $listValue, $properties);
300
            }
301
302
            // Else: If the value is not empty
303 4
        } elseif ($value) {
304 4
            $properties[$name]->values[] = $value;
305
        }
306 4
    }
307
308
    /**
309
     * Process a property value object
310
     *
311
     * @param string $name      Property name
312
     * @param \stdClass $value  Property value
313
     * @param array $properties Properties
314
     */
315 3
    protected function processNodePropertyObject($name, $value, array &$properties)
316
    {
317 3
        if (!empty($value->type) || !empty($value->lang)) {
318 3
            $properties[$name]->values[] = $value;
319
320
            // @type = @id
321 3
        } elseif (!empty($value->id)) {
322 3
            $properties[$name]->values[] = $value->id;
323
        }
324 3
    }
325
326
    /**
327
     * Parse a JSON-LD fragment
328
     *
329
     * @param NodeInterface|LanguageTaggedString|TypedValue|array $jsonLD JSON-LD fragment
330
     *
331
     * @return \stdClass|string|array Parsed fragment
332
     */
333 4
    protected function parse($jsonLD)
334
    {
335
        // If it's a node object
336 4
        if ($jsonLD instanceof NodeInterface) {
337 4
            return $this->parseNode($jsonLD);
338
339
            // Else if it's a language tagged string
340 3
        } elseif ($jsonLD instanceof LanguageTaggedString) {
341 1
            return $this->parseLanguageTaggedString($jsonLD);
342
343
            // Else if it's a typed value
344 3
        } elseif ($jsonLD instanceof TypedValue) {
345 3
            return $this->parseTypedValue($jsonLD);
346
        }
347
348
        // Else if it's a list of items
349 2
        return array_map([$this, 'parse'], $jsonLD);
350
    }
351
352
    /**
353
     * Parse a language tagged string
354
     *
355
     * @param LanguageTaggedString $value Language tagged string
356
     *
357
     * @return \stdClass Value
358
     */
359 1
    protected function parseLanguageTaggedString(LanguageTaggedString $value)
360
    {
361 1
        return (object)['value' => $value->getValue(), 'lang' => $value->getLanguage()];
362
    }
363
364
    /**
365
     * Parse a typed value
366
     *
367
     * @param TypedValue $value Typed value
368
     *
369
     * @return string Value
370
     */
371 3
    protected function parseTypedValue(TypedValue $value)
372
    {
373 3
        return $value->getValue();
374
    }
375
376 7
    private function sanitizeJsonSource($jsonLDDocSource)
377
    {
378 7
        $jsonLDDocSource = trim($jsonLDDocSource);
379
380 7
        if (substr($jsonLDDocSource, -1) === ';') {
381 2
            $jsonLDDocSource = substr_replace($jsonLDDocSource, '', -1);
382
        }
383
384 7
        return $jsonLDDocSource;
385
    }
386
}
387