1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\SchemaOrg\Decoder; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
use Spatie\SchemaOrg\BaseType; |
7
|
|
|
|
8
|
|
View Code Duplication |
class LdJson |
|
|
|
|
9
|
|
|
{ |
10
|
|
|
public static function fromJson(string $json): BaseType |
11
|
|
|
{ |
12
|
|
|
$data = json_decode($json, true); |
13
|
|
|
|
14
|
|
|
return static::fromArray($data); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public static function fromArray(array $data): BaseType |
18
|
|
|
{ |
19
|
|
|
if (!isset($data['@context'])) { |
20
|
|
|
throw new InvalidArgumentException('no @context'); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
if (strpos($data['@context'], 'schema.org') === false) { |
24
|
|
|
throw new InvalidArgumentException('@context invalid'); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
if (!isset($data['@type'])) { |
28
|
|
|
throw new InvalidArgumentException('no @type'); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
unset($data['@context']); |
32
|
|
|
return static::generateType($data); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
protected static function generateType(array $data): BaseType |
36
|
|
|
{ |
37
|
|
|
if (!isset($data['@type'])) { |
38
|
|
|
throw new InvalidArgumentException('no @type'); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$fqcn = '\\Spatie\\SchemaOrg\\' . $data['@type']; |
42
|
|
|
unset($data['@type']); |
43
|
|
|
if (!static::isValidType($fqcn)) { |
44
|
|
|
throw new InvalidArgumentException('type does not exist'); |
45
|
|
|
} |
46
|
|
|
/** @var BaseType $type */ |
47
|
|
|
$type = new $fqcn(); |
48
|
|
|
|
49
|
|
|
foreach ($data as $property => $value) { |
50
|
|
|
if(is_array($value)) { |
51
|
|
|
if(isset($value['@type'])) { |
52
|
|
|
$type->setProperty($property, static::generateType($value)); |
53
|
|
|
continue; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$type->setProperty($property, array_map(function ($value) { |
57
|
|
|
if(is_array($value) && isset($value['@type'])) { |
58
|
|
|
return static::generateType($value); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return $value; |
62
|
|
|
}, $value)); |
63
|
|
|
continue; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$type->setProperty($property, $value); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $type; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
protected static function isValidType(string $fqcn): bool |
73
|
|
|
{ |
74
|
|
|
return class_exists($fqcn); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.