forked from dunglas/solid-client-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonLdParser.php
More file actions
64 lines (55 loc) · 1.64 KB
/
JsonLdParser.php
File metadata and controls
64 lines (55 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
/*
* This file is part of the Solid Client PHP project.
* (c) Kévin Dunglas <kevin@dunglas.fr>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Dunglas\PhpSolidClient;
/**
* Parses JSON-LD responses from Solid/CSS servers.
*
* CSS returns expanded JSON-LD by default for Accept: application/ld+json,
* so a full JSON-LD processor is not needed — json_decode is sufficient.
* Relative @id values should be resolved using IriHelper.
*/
final class JsonLdParser
{
/**
* Parses a JSON-LD string into an array of node arrays.
*
* Handles both single objects and arrays of objects.
*
* @return list<array<string, mixed>>
*/
public static function parse(string $jsonLd): array
{
$decoded = json_decode($jsonLd, true, 512, \JSON_THROW_ON_ERROR);
// If it's a single object (has @id or @type), wrap in array
if (isset($decoded['@id']) || isset($decoded['@type'])) {
return [$decoded];
}
// If it's an array of objects (expanded form)
if (array_is_list($decoded)) {
return $decoded;
}
return [$decoded];
}
/**
* Finds a node by @id in parsed JSON-LD.
*
* @param list<array<string, mixed>> $nodes
*
* @return array<string, mixed>|null
*/
public static function findById(array $nodes, string $id): ?array
{
foreach ($nodes as $node) {
if (($node['@id'] ?? null) === $id) {
return $node;
}
}
return null;
}
}