-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathStructuredDataService.php
More file actions
233 lines (188 loc) · 7.09 KB
/
StructuredDataService.php
File metadata and controls
233 lines (188 loc) · 7.09 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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
<?php
namespace Justbetter\StatamicStructuredData\Services;
use Justbetter\StatamicStructuredData\Parser\StructuredDataParser;
use Justbetter\StatamicStructuredData\Services\Transformers\FieldTransformerFactory;
use Statamic\Contracts\Entries\Entry as EntryContract;
use Statamic\Contracts\Taxonomies\Term as TermContract;
use Statamic\Entries\Entry as EntryModel;
use Statamic\Facades\Entry as EntryFacade;
use Statamic\Structures\Page;
use Statamic\Taxonomies\LocalizedTerm;
class StructuredDataService
{
protected StructuredDataParser $parser;
protected FieldTransformerFactory $transformerFactory;
public function __construct(StructuredDataParser $parser)
{
$this->parser = $parser;
$this->transformerFactory = new FieldTransformerFactory;
}
/**
* @param EntryContract|Page|LocalizedTerm $item
* @return array<int, string>
*/
public function getJsonLdScripts($item, bool $json = false): array
{
$templates = $this->getTemplates($item);
if (! $templates) {
return [];
}
$scripts = [];
foreach ($templates as $templateId) {
$template = EntryFacade::find($templateId);
if (! $template instanceof EntryModel) {
continue;
}
/** @var array<int, array<string, mixed>>|null $schemas */
$schemas = $template->get('schema_data');
$schemas = $schemas ?? [];
if (empty($schemas) || ! is_array($schemas)) {
continue;
}
try {
$parsedSchemas = $this->parser->parse($schemas, $item);
if (! is_array($parsedSchemas)) {
continue;
}
foreach ($parsedSchemas as $parsedSchema) {
if (! is_array($parsedSchema)) {
continue;
}
$scripts[] = $this->formatJsonLd($parsedSchema, $json, $item);
}
} catch (\Exception $e) {
continue;
}
}
return $scripts;
}
/**
* @param array<string, mixed> $schema
*/
public function formatJsonLd(array $schema, bool $json = false, EntryContract|Page|LocalizedTerm|null $item = null): string
{
$transformedSchema = $this->transformSchema($schema, $item);
$encodedSchema = json_encode($transformedSchema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($json) {
return $encodedSchema ?: '';
}
return sprintf(
'<script type="application/ld+json">%s</script>',
$encodedSchema ?: ''
);
}
/**
* @param mixed $schemas
* @return array<int, array<string, mixed>>
*/
public function parseAndTransformSchemas($schemas, EntryContract|Page|LocalizedTerm|TermContract|null $item = null): array
{
$parsedData = $this->parser->parse($schemas, $item);
$transformedData = [];
if (is_array($parsedData)) {
foreach ($parsedData as $schema) {
if (is_array($schema)) {
$transformedData[] = $this->transformSchema($schema, $item);
}
}
}
return $transformedData;
}
/**
* @param array<string, mixed> $schema
* @return array<string, mixed>
*/
public function transformSchema(array $schema, EntryContract|Page|LocalizedTerm|TermContract|null $item = null): array
{
$result = [];
if (isset($schema['specialProps']) && is_array($schema['specialProps'])) {
$specialProps = $schema['specialProps'];
if (isset($specialProps['context'])) {
$result['@context'] = $specialProps['context'];
}
if (isset($specialProps['type'])) {
$result['@type'] = $specialProps['type'];
}
if (isset($specialProps['id'])) {
$result['@id'] = $specialProps['id'];
}
}
if (isset($schema['fields']) && is_array($schema['fields'])) {
foreach ($schema['fields'] as $field) {
if (! isset($field['key'])) {
continue;
}
$key = $field['key'];
$transformedValue = $this->transformField($field, $item, $result);
if ($transformedValue === null) {
continue;
}
$result[$key] = $transformedValue;
}
}
return $result;
}
protected function isAssociativeArray(array $array): bool
{
if (empty($array)) {
return false;
}
return array_keys($array) !== range(0, count($array) - 1);
}
/**
* @param array<string, mixed> $field
* @param array<string, mixed> $result
*/
protected function transformField(array $field, EntryContract|Page|LocalizedTerm|TermContract|null $item = null, array &$result = []): mixed
{
$type = $field['type'] ?? null;
// Handle object and object_array types that need recursive schema transformation
if ($type === 'object' && isset($field['value']) && is_array($field['value'])) {
return $this->transformSchema($field['value'], $item);
}
if ($type === 'object_array' && isset($field['values']) && is_array($field['values'])) {
$output = [];
foreach ($field['values'] as $value) {
if (is_array($value)) {
$output[] = $this->transformSchema($value, $item);
}
}
return $output;
}
// Use transformer factory for all other field types
$transformer = $this->transformerFactory->getTransformer(is_string($type) ? $type : null);
$transformedValue = $transformer->transform($field, $item);
// Handle flat mode for replicator_object_array
if ($type === 'replicator_object_array'
&& isset($field['config']['flat'])
&& $field['config']['flat'] === true
&& is_array($transformedValue)
&& $this->isAssociativeArray($transformedValue)) {
$result = array_merge($result, $transformedValue);
return null;
}
return $transformedValue;
}
/**
* @param EntryContract|Page|LocalizedTerm|mixed $item
* @return array<int|string, mixed>
*/
protected function getTemplates($item): array
{
if ($item instanceof Page) {
/** @var EntryContract $item */
$item = $item->entry();
}
if ($item instanceof EntryModel) {
/** @var array<int|string, mixed>|null $templates */
$templates = $item->get('structured_data_templates');
return is_array($templates) ? $templates : [];
}
if ($item instanceof LocalizedTerm) {
/** @var array<int|string, mixed>|null $templates */
$templates = $item->get('structured_data_templates');
return is_array($templates) ? $templates : [];
}
return [];
}
}