Completed
Branch master (6c7c3c)
by Joschi
02:33
created

JsonLD::processNodeProperty()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 4
nop 3
crap 4
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 © 2017 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 © 2017 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
     * Vocabulary cache
64
     *
65
     * @var VocabularyCache
66
     */
67
    protected $vocabularyCache;
68
    /**
69
     * Context loader
70
     *
71
     * @var CachingContextLoader
72
     */
73
    protected $contextLoader;
74
    /**
75
     * Format
76
     *
77
     * @var int
78
     */
79
    const FORMAT = Format::JSON_LD;
80
    /**
81
     * Regex pattern for matching leading comments in a JSON string
82
     *
83
     * @var string
84
     */
85
    const JSON_COMMENT_PATTERN = '#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#';
86
87
    /**
88
     * JSON-LD parser constructor
89
     *
90
     * @param UriInterface $uri Base URI
91
     * @param LoggerInterface $logger Logger
92
     */
93 5
    public function __construct(UriInterface $uri, LoggerInterface $logger)
94
    {
95 5
        parent::__construct($uri, $logger);
96 5
        $this->vocabularyCache = new VocabularyCache();
97 5
        $this->contextLoader = new CachingContextLoader($this->vocabularyCache);
98 5
    }
99
100
    /**
101
     * Parse a DOM document
102
     *
103
     * @param \DOMDocument $dom DOM Document
104
     * @return ParsingResultInterface Micro information items
105
     */
106 4
    public function parseDom(\DOMDocument $dom)
107
    {
108 4
        $this->logger->info('Running parser: '.(new \ReflectionClass(__CLASS__))->getShortName());
109 4
        $items = [];
110
111
        // Find and process all JSON-LD documents
112 4
        $xpath = new \DOMXPath($dom);
113 4
        $jsonLDDocs = $xpath->query('//*[local-name(.) = "script"][@type = "application/ld+json"]');
114 4
        $this->logger->debug('Processing '.$jsonLDDocs->length.' JSON-LD documents');
115
116
        // Run through all JSON-LD documents
117 4
        foreach ($jsonLDDocs as $jsonLDDoc) {
118 4
            $jsonLDDocSource = preg_replace(self::JSON_COMMENT_PATTERN, '', $jsonLDDoc->textContent);
119 4
            $i = $this->parseDocument($jsonLDDocSource);
120 3
            $items = array_merge($items, $i);
121
        }
122
123 3
        return new ParsingResult(self::FORMAT, $items);
124
    }
125
126
    /**
127
     * Parse a JSON-LD document
128
     *
129
     * @param string $jsonLDDocSource JSON-LD document
130
     * @return array Items
131
     */
132 4
    protected function parseDocument($jsonLDDocSource)
133
    {
134
        // Unserialize the JSON-LD document
135 4
        $jsonLDDoc = @json_decode($jsonLDDocSource);
136
137
        // If this is not a valid JSON document: Return
138 4
        if (!is_object($jsonLDDoc) && !is_array($jsonLDDoc)) {
139 3
            $this->logger->error('Skipping invalid JSON-LD document');
140 2
            return [];
141
        }
142
143
        // Parse the document
144 2
        return array_filter(
145 2
            is_array($jsonLDDoc) ?
146 2
                array_map([$this, 'parseRootNode'], $jsonLDDoc) : [$this->parseRootNode($jsonLDDoc)]
147
        );
148
    }
149
150
    /**
151
     * Parse a JSON-LD root node
152
     *
153
     * @param \stdClass $jsonLDRoot JSON-LD root node
154
     */
155 2
    protected function parseRootNode($jsonLDRoot)
156
    {
157 2
        $item = null;
158
159
        try {
160 2
            $jsonDLDocument = JsonLDParser::getDocument($jsonLDRoot, ['documentLoader' => $this->contextLoader]);
161
162
            // Run through all nodes to parse the first one
163
            /** @var Node $node */
164 2
            foreach ($jsonDLDocument->getGraph()->getNodes() as $node) {
165 2
                $item = $this->parseNode($node);
166 2
                break;
167
            }
168 1
        } catch (JsonLdException $e) {
169 1
            $this->logger->error($e->getMessage(), ['exception' => $e]);
170
        }
171
172 2
        return $item;
173
    }
174
175
    /**
176
     * Parse a JSON-LD fragment
177
     *
178
     * @param NodeInterface|LanguageTaggedString|TypedValue|array $jsonLD JSON-LD fragment
179
     * @return \stdClass|string|array Parsed fragment
180
     */
181 2
    protected function parse($jsonLD)
182
    {
183
        // If it's a node object
184 2
        if ($jsonLD instanceof NodeInterface) {
185 2
            return $this->parseNode($jsonLD);
186
187
            // Else if it's a language tagged string
188 2
        } elseif ($jsonLD instanceof LanguageTaggedString) {
189 1
            return $this->parseLanguageTaggedString($jsonLD);
190
191
            // Else if it's a typed value
192 2
        } elseif ($jsonLD instanceof TypedValue) {
193 2
            return $this->parseTypedValue($jsonLD);
194
        }
195
196
        // Else if it's a list of items
197
        //elseif (is_array($jsonLD)) {
198 1
        return array_map([$this, 'parse'], $jsonLD);
199
//      }
200
    }
201
202
    /**
203
     * Parse a JSON-LD node
204
     *
205
     * @param NodeInterface $node Node
206
     * @return \stdClass Item
207
     */
208 2
    protected function parseNode(NodeInterface $node)
209
    {
210
        return (object)[
211 2
            'type' => $this->parseNodeType($node),
212 2
            'id' => $node->getId() ?: null,
213 2
            'properties' => $this->parseNodeProperties($node),
214
        ];
215
    }
216
217
    /**
218
     * Parse the type of a JSON-LD node
219
     *
220
     * @param NodeInterface $node Node
221
     * @return array Item type
222
     */
223 2
    protected function parseNodeType(NodeInterface $node)
224
    {
225
        /** @var Node $itemType */
226 2
        return ($itemType = $node->getType()) ? [$this->vocabularyCache->expandIRI($itemType->getId())] : [];
227
    }
228
229
    /**
230
     * Parse the properties of a JSON-LD node
231
     *
232
     * @param NodeInterface $node Node
233
     * @return array Item properties
234
     */
235 2
    protected function parseNodeProperties(NodeInterface $node)
236
    {
237 2
        $properties = [];
238
239
        // Run through all node properties
240 2
        foreach ($node->getProperties() as $name => $property) {
241
            // Skip the node type
242 2
            if ($name === Node::TYPE) {
243 2
                continue;
244
            }
245
246
            // Initialize the property (if necessary)
247 2
            $this->initializeNodeProperty($name, $properties);
248
249
            // Parse and process the property value
250 2
            $this->processNodeProperty($name, $this->parse($property), $properties);
251
        }
252
253 2
        return $properties;
254
    }
255
256
    /**
257
     * Initialize a JSON-LD node property (if necessary)
258
     *
259
     * @param string $name Property name
260
     * @param array $properties Item properties
261
     */
262 2
    protected function initializeNodeProperty($name, array &$properties)
263
    {
264 2
        if (empty($properties[$name])) {
265 2
            $properties[$name] = $this->vocabularyCache->expandIRI($name);
266 2
            $properties[$name]->values = [];
267
        }
268 2
    }
269
270
    /**
271
     * Process a property value
272
     *
273
     * @param string $name Property name
274
     * @param \stdClass|array|string $value Property value
275
     * @param array $properties Item properties
276
     */
277 2
    protected function processNodeProperty($name, $value, array &$properties)
278
    {
279
        // If this is a nested item
280 2
        if (is_object($value)) {
281 2
            $this->processNodePropertyObject($name, $value, $properties);
282
283
            // Else: If this is a value list
284 2
        } elseif (is_array($value)) {
285 1
            $properties[$name]->values = array_merge($properties[$name]->values, $value);
286
287
            // Else: If the value is not empty
288 2
        } elseif ($value) {
289 2
            $properties[$name]->values[] = $value;
290
        }
291 2
    }
292
293
    /**
294
     * Process a property value object
295
     *
296
     * @param string $name Property name
297
     * @param \stdClass $value Property value
298
     * @param array $properties Properties
299
     */
300 2
    protected function processNodePropertyObject($name, $value, array &$properties)
301
    {
302 2
        if (!empty($value->type) || !empty($value->lang)) {
303 2
            $properties[$name]->values[] = $value;
304
305
            // @type = @id
306 2
        } elseif (!empty($value->id)) {
307 2
            $properties[$name]->values[] = $value->id;
308
        }
309 2
    }
310
311
    /**
312
     * Parse a language tagged string
313
     *
314
     * @param LanguageTaggedString $value Language tagged string
315
     * @return \stdClass Value
316
     */
317 1
    protected function parseLanguageTaggedString(LanguageTaggedString $value)
318
    {
319 1
        return (object)['value' => $value->getValue(), 'lang' => $value->getLanguage()];
320
    }
321
322
    /**
323
     * Parse a typed value
324
     *
325
     * @param TypedValue $value Typed value
326
     * @return string Value
327
     */
328 2
    protected function parseTypedValue(TypedValue $value)
329
    {
330 2
        return $value->getValue();
331
    }
332
}
333