Completed
Push — master ( 316a87...f7834c )
by Joschi
03:28
created

JsonLD::initializeNodeProperty()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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