-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
ThingConverter.php
120 lines (97 loc) · 2.81 KB
/
ThingConverter.php
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
declare(strict_types=1);
namespace Brick\Schema;
use Brick\Schema\Interfaces\Thing;
use Brick\StructuredData\Item;
class ThingConverter
{
/**
* @var ObjectFactory
*/
private $objectFactory;
/**
* ThingConverter constructor.
*/
public function __construct()
{
$properties = require __DIR__ . '/../data/properties.php';
$this->objectFactory = new ObjectFactory($properties);
}
/**
* Converts structured data Items to schema.org Things.
*
* Items that do not match a schema.org Thing will be skipped.
*
* @param Item[] $items
*
* @return Thing[]
*/
public function convertItemsToThings(array $items) : array
{
$things = array_map(function(Item $item) {
return $this->convertItemToThing($item);
}, $items);
$things = array_filter($things);
$things = array_values($things);
return $things;
}
/**
* Converts a structured data Item to a schema.org Thing.
*
* If the types of the item do not match a schema.org Thing, this method returns null.
*
* @param Item $item
*
* @return Thing|null
*/
public function convertItemToThing(Item $item) : ?Thing
{
$types = [];
foreach ($item->getTypes() as $type) {
$type = $this->schemaOrgIdToLabel($type);
if ($type !== null) {
$types[] = $type;
}
}
$thing = $this->objectFactory->build($types);
if ($thing === null) {
return null;
}
foreach ($item->getProperties() as $name => $values) {
$name = $this->schemaOrgIdToLabel($name);
if ($name === null) {
continue;
}
if (isset($thing->{$name})) {
/** @var SchemaTypeList $schemaTypeList */
$schemaTypeList = $thing->{$name};
foreach ($values as $value) {
if ($value instanceof Item) {
$value = $this->convertItemToThing($value);
if ($value === null) {
continue;
}
}
$schemaTypeList->addValue($value);
}
}
}
return $thing;
}
/**
* Converts a schema.org ID to a label.
*
* e.g. http://schema.org/Product => Product
*
* @param string $schemaOrgId
*
* @return string|null The label, or null if not a valid schema.org id.
*/
private function schemaOrgIdToLabel(string $schemaOrgId) : ?string
{
if (preg_match('/https?\:\/\/schema.org\/([A-Za-z0-9]+)$/', $schemaOrgId, $matches) === 1) {
return $matches[1];
}
return null;
}
}