Completed
Pull Request — master (#63)
by Richard van
08:48
created

JsonLD::sanitizeJsonSource()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 0
cp 0
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
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 6
    /**
94
     * JSON-LD parser constructor
95 6
     *
96 6
     * @param UriInterface $uri       Base URI
97 6
     * @param LoggerInterface $logger Logger
98 6
     */
99
    public function __construct(UriInterface $uri, LoggerInterface $logger)
100
    {
101
        parent::__construct($uri, $logger);
102
        $this->vocabularyCache = new VocabularyCache();
103
        $this->contextLoader   = new CachingContextLoader($this->vocabularyCache);
104
    }
105
106
    /**
107
     * Parse a DOM document
108 5
     *
109
     * @param \DOMDocument $dom DOM Document
110 5
     *
111 5
     * @return ParsingResultInterface Micro information items
112
     * @throws \ReflectionException
113
     */
114 5
    public function parseDom(\DOMDocument $dom)
115 5
    {
116 5
        $this->logger->info('Running parser: '.(new \ReflectionClass(__CLASS__))->getShortName());
117
        $items = [];
118
119 5
        // Find and process all JSON-LD documents
120 5
        $xpath      = new \DOMXPath($dom);
121 5
        $jsonLDDocs = $xpath->query('//*[local-name(.) = "script"][@type = "application/ld+json"]');
122 4
        $this->logger->debug('Processing '.$jsonLDDocs->length.' JSON-LD documents');
123
124
        // Run through all JSON-LD documents
125 4
        foreach ($jsonLDDocs as $jsonLDDoc) {
126
            $jsonLDDocSource = preg_replace(self::JSON_COMMENT_PATTERN, '', $jsonLDDoc->textContent);
127
            $i               = $this->parseDocument($jsonLDDocSource);
128
            $items           = array_merge($items, $i);
129
        }
130
131
        return new ParsingResult(self::FORMAT, $items);
132
    }
133
134
    /**
135 5
     * Parse a JSON-LD document
136
     *
137 5
     * @param string $jsonLDDocSource JSON-LD document
138
     *
139
     * @return array Items
140 5
     */
141
    protected function parseDocument($jsonLDDocSource)
142
    {
143 5
        $jsonLDDocSource = $this->sanitizeJsonSource($jsonLDDocSource);
144 3
145
        // Unserialize the JSON-LD document
146 2
        $jsonLDDoc = @json_decode($jsonLDDocSource);
147
148
        // If this is not a valid JSON document: Return
149
        if (!is_object($jsonLDDoc) && !is_array($jsonLDDoc)) {
150 3
            $this->logger->error('Skipping invalid JSON-LD document');
151 3
152 3
            return [];
153
        }
154
155
        // Parse the document
156
        return array_filter(
157
            is_array($jsonLDDoc) ?
158
                array_map([$this, 'parseRootNode'], $jsonLDDoc) : [$this->parseRootNode($jsonLDDoc)]
159
        );
160
    }
161 3
162
    /**
163 3
     * Parse a JSON-LD root node
164
     *
165
     * @param \stdClass $jsonLDRoot JSON-LD root node
166 3
     */
167
    protected function parseRootNode($jsonLDRoot)
168
    {
169
        $item = null;
170 3
171 3
        try {
172 3
            $jsonDLDocument = JsonLDParser::getDocument($jsonLDRoot, ['documentLoader' => $this->contextLoader]);
173
174
            // Run through all nodes to parse the first one
175
            /** @var Node $node */
176
            foreach ($jsonDLDocument->getGraph()->getNodes() as $node) {
177
                $item = $this->parseNode($node);
178 3
                break;
179
            }
180
        } catch (JsonLdException $exception) {
181
            $this->logger->error($exception->getMessage(), ['exception' => $exception]);
182
        }
183
184
        return $item;
185
    }
186
187
    /**
188 3
     * Parse a JSON-LD node
189
     *
190
     * @param NodeInterface $node Node
191 3
     *
192 3
     * @return \stdClass|string Item or string ID
193 3
     */
194
    protected function parseNode(NodeInterface $node)
195
    {
196
        $nodeId = $node->getId() ?: null;
197
198
        // if ID is in the current chain, just return the ID reference
199
        if (in_array($node, $this->chain, true)) {
200
            return $nodeId;
201
        }
202
203
        // add node to chain, parse node tree, remove node from chain
204 3
        $this->chain[] = $node;
205
        $properties = $this->parseNodeProperties($node);
206 3
        array_pop($this->chain);
207 1
208
        return (object)[
209
            'type'       => $this->parseNodeType($node),
210
            'id'         => $nodeId,
211 3
            'properties' => $properties,
212 3
        ];
213 3
    }
214
215 3
    /**
216 2
     * Parse the type of a JSON-LD node
217
     *
218
     * @param NodeInterface $node Node
219 3
     *
220 3
     * @return array Item type
221 3
     */
222
    protected function parseNodeType(NodeInterface $node): array
223
    {
224 3
        if ($node->isBlankNode()) {
225
            return [];
226
        }
227
228
        /** @var NodeInterface|NodeInterface[] $itemTypes */
229
        $itemTypes = $node->getType();
230
        $itemTypes = is_array($itemTypes) ? $itemTypes : [$itemTypes];
231
        $itemTypes = array_filter($itemTypes);
232
233
        if (empty($itemTypes)) {
234 3
            return [];
235
        }
236 3
237
        $types = [];
238
        foreach ($itemTypes as $itemType) {
239 3
            $types[] = $this->vocabularyCache->expandIRI($itemType->getId());
240
        }
241 3
242 3
        return $types;
243
    }
244
245
    /**
246 2
     * Parse the properties of a JSON-LD node
247
     *
248
     * @param NodeInterface $node Node
249 2
     *
250
     * @return array Item properties
251
     */
252 3
    protected function parseNodeProperties(NodeInterface $node)
253
    {
254
        $properties = [];
255
256
        // Run through all node properties
257
        foreach ($node->getProperties() as $name => $property) {
258
            // Skip the node type
259
            if ($name === Node::TYPE) {
260
                continue;
261 2
            }
262
263 2
            // Initialize the property (if necessary)
264 2
            $this->initializeNodeProperty($name, $properties);
265 2
266
            // Parse and process the property value
267 2
            $this->processNodeProperty($name, $this->parse($property), $properties);
268
        }
269
270
        return $properties;
271
    }
272
273
    /**
274
     * Initialize a JSON-LD node property (if necessary)
275
     *
276 2
     * @param string $name      Property name
277
     * @param array $properties Item properties
278
     */
279 2
    protected function initializeNodeProperty($name, array &$properties)
280 2
    {
281
        if (empty($properties[$name])) {
282
            $properties[$name]         = $this->vocabularyCache->expandIRI($name);
283 2
            $properties[$name]->values = [];
284 2
        }
285 2
    }
286
287
    /**
288
     * Process a property value
289 2
     *
290 2
     * @param string $name                  Property name
291
     * @param \stdClass|array|string $value Property value
292 2
     * @param array $properties             Item properties
293
     */
294
    protected function processNodeProperty($name, $value, array &$properties)
295
    {
296
        // If this is a nested item
297
        if (is_object($value)) {
298
            $this->processNodePropertyObject($name, $value, $properties);
299
300
            // Else: If this is a value list
301 2
        } elseif (is_array($value)) {
302
            foreach ($value as $listValue) {
303 2
                $this->processNodeProperty($name, $listValue, $properties);
304 2
            }
305
306
            // Else: If the value is not empty
307 2
        } elseif ($value) {
308 2
            $properties[$name]->values[] = $value;
309
        }
310 2
    }
311
312
    /**
313
     * Process a property value object
314
     *
315
     * @param string $name      Property name
316
     * @param \stdClass $value  Property value
317
     * @param array $properties Properties
318
     */
319 2
    protected function processNodePropertyObject($name, $value, array &$properties)
320
    {
321
        if (!empty($value->type) || !empty($value->lang)) {
322 2
            $properties[$name]->values[] = $value;
323 2
324
            // @type = @id
325
        } elseif (!empty($value->id)) {
326 2
            $properties[$name]->values[] = $value->id;
327 1
        }
328
    }
329
330 2
    /**
331 2
     * Parse a JSON-LD fragment
332
     *
333
     * @param NodeInterface|LanguageTaggedString|TypedValue|array $jsonLD JSON-LD fragment
334
     *
335 2
     * @return \stdClass|string|array Parsed fragment
336
     */
337
    protected function parse($jsonLD)
338
    {
339
        // If it's a node object
340
        if ($jsonLD instanceof NodeInterface) {
341
            return $this->parseNode($jsonLD);
342
343
            // Else if it's a language tagged string
344
        } elseif ($jsonLD instanceof LanguageTaggedString) {
345 1
            return $this->parseLanguageTaggedString($jsonLD);
346
347 1
            // Else if it's a typed value
348
        } elseif ($jsonLD instanceof TypedValue) {
349
            return $this->parseTypedValue($jsonLD);
350
        }
351
352
        // Else if it's a list of items
353
        return array_map([$this, 'parse'], $jsonLD);
354
    }
355
356
    /**
357 2
     * Parse a language tagged string
358
     *
359 2
     * @param LanguageTaggedString $value Language tagged string
360
     *
361
     * @return \stdClass Value
362 5
     */
363
    protected function parseLanguageTaggedString(LanguageTaggedString $value)
364 5
    {
365
        return (object)['value' => $value->getValue(), 'lang' => $value->getLanguage()];
366 5
    }
367 1
368
    /**
369
     * Parse a typed value
370 5
     *
371
     * @param TypedValue $value Typed value
372
     *
373
     * @return string Value
374
     */
375
    protected function parseTypedValue(TypedValue $value)
376
    {
377
        return $value->getValue();
378
    }
379
380
    private function sanitizeJsonSource($jsonLDDocSource)
381
    {
382
        $jsonLDDocSource = trim($jsonLDDocSource);
383
384
        if (substr($jsonLDDocSource, -1) === ';') {
385
            $jsonLDDocSource = substr_replace($jsonLDDocSource, '', -1);
386
        }
387
388
        return $jsonLDDocSource;
389
    }
390
}
391