-
-
Notifications
You must be signed in to change notification settings - Fork 88
/
SitemapWriter.php
329 lines (267 loc) · 9.21 KB
/
SitemapWriter.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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
<?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\Exporter\Writer;
/**
* Generates a sitemap site from.
*/
final class SitemapWriter implements WriterInterface
{
public const LIMIT_SIZE = 10_485_760;
public const LIMIT_URL = 50000;
private string $folder;
private string $pattern;
private string $groupName;
private bool $autoIndex;
/**
* @var resource|null
*
* @phpstan-var resource|null
* @psalm-var resource|closed-resource|null
*/
private $buffer;
/**
* @var string[]
*/
private array $headers;
private int $bufferSize = 0;
private int $bufferUrlCount = 0;
private int $bufferPart = 0;
/**
* @param string $folder The folder to store the sitemap.xml file
* @param mixed $groupName Name of sub-sitemap (optional)
* @param string[] $headers Indicate the need for namespace in the header sitemap
* @param bool $autoIndex If you want to generate index of sitemap (optional)
*/
public function __construct(string $folder, $groupName = false, array $headers = [], bool $autoIndex = true)
{
$this->folder = $folder;
$this->groupName = \is_string($groupName) ? $groupName : '';
$this->headers = $headers;
$this->autoIndex = $autoIndex;
$this->pattern = 'sitemap_'.('' !== $this->groupName ? $this->groupName.'_' : '').'%05d.xml';
}
/**
* Returns the status of auto generation of index site map.
*/
public function isAutoIndex(): bool
{
return $this->autoIndex;
}
/**
* Returns folder to store the sitemap.xml file.
*/
public function getFolder(): string
{
return $this->folder;
}
public function open(): void
{
$this->bufferPart = 0;
$this->generateNewPart();
}
public function write(array $data): void
{
$data = $this->buildData($data);
switch ($data['type']) {
case 'video':
$line = $this->generateVideoLine($data);
break;
case 'image':
$line = $this->generateImageLine($data);
break;
case 'default':
default:
$line = $this->generateDefaultLine($data);
}
$this->addSitemapLine($line);
}
public function close(): void
{
if (null !== $this->buffer) {
$this->closeSitemap();
}
if ($this->autoIndex) {
self::generateSitemapIndex(
$this->folder,
'sitemap_'.('' !== $this->groupName ? $this->groupName.'_' : '').'*.xml',
'sitemap'.('' !== $this->groupName ? '_'.$this->groupName : '').'.xml'
);
}
}
/**
* Generates the sitemap index from the sitemap part avaible in the folder.
*
* @param string $folder A folder to write sitemap index
* @param string $baseUrl A base URL
* @param string $pattern A sitemap pattern, optional
* @param string $filename A sitemap file name, optional
*/
public static function generateSitemapIndex(string $folder, string $baseUrl, string $pattern = 'sitemap*.xml', string $filename = 'sitemap.xml'): void
{
$content = "<?xml version='1.0' encoding='UTF-8'?>\n<sitemapindex xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.sitemaps.org/schemas/sitemap/1.0 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd' xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>\n";
foreach (glob(sprintf('%s/%s', $folder, $pattern)) as $file) {
$stat = stat($file);
$content .= sprintf(
"\t".'<sitemap><loc>%s/%s</loc><lastmod>%s</lastmod></sitemap>'."\n",
$baseUrl,
basename($file),
date('Y-m-d', $stat['mtime'])
);
}
$content .= '</sitemapindex>';
file_put_contents(sprintf('%s/%s', $folder, $filename), $content);
}
/**
* Generate a new sitemap part.
*
* @throws \RuntimeException
*/
private function generateNewPart(): void
{
if (null !== $this->buffer) {
$this->closeSitemap();
}
$this->bufferUrlCount = 0;
$this->bufferSize = 0;
++$this->bufferPart;
if (!is_writable($this->folder)) {
throw new \RuntimeException(sprintf('Unable to write to folder: %s', $this->folder));
}
$filename = sprintf($this->pattern, $this->bufferPart);
$this->buffer = fopen($this->folder.'/'.$filename, 'w');
$this->bufferSize += fwrite($this->buffer, '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'.$this->getHeaderByFlag().'>'."\n");
}
/**
* Add a new line into the sitemap part.
*/
private function addSitemapLine(string $line): void
{
if ($this->bufferUrlCount >= self::LIMIT_URL) {
$this->generateNewPart();
}
if (($this->bufferSize + \strlen($line) + 9) > self::LIMIT_SIZE) {
$this->generateNewPart();
}
++$this->bufferUrlCount;
$this->bufferSize += fwrite($this->buffer, $line);
}
/**
* Build data with default parameters.
*
* @param array<string, mixed> $data List of parameters
*
* @return array<string, mixed>
*/
private function buildData(array $data): array
{
$default = [
'url' => null,
'lastmod' => 'now',
'changefreq' => 'weekly',
'priority' => 0.5,
'type' => 'default',
];
$data = array_merge($default, $data);
$this->fixDataType($data);
return $data;
}
/**
* Fix type of data, if data type is specific,
* he must to be defined in data and he must to be a array.
*
* @param array<string, mixed> $data List of parameters
*/
private function fixDataType(array &$data): void
{
if ('default' === $data['type']) {
return;
}
$valid_var_name = [
'image' => 'images',
'video' => 'video',
];
if (
!isset($valid_var_name[$data['type']], $data[$valid_var_name[$data['type']]])
|| !\is_array($data[$valid_var_name[$data['type']]])
) {
$data['type'] = 'default';
}
}
/**
* Generate standard line of sitemap.
*
* @param array<string, mixed> $data List of parameters
*/
private function generateDefaultLine(array $data): string
{
return sprintf(' <url><loc>%s</loc><lastmod>%s</lastmod><changefreq>%s</changefreq><priority>%s</priority></url>'."\n", $data['url'], date('Y-m-d', strtotime($data['lastmod'])), $data['changefreq'], $data['priority']);
}
/**
* Generate image line of sitemap.
*
* @param array<string, mixed> $data List of parameters
*/
private function generateImageLine(array $data): string
{
$images = '';
if (\count($data['images']) > 1000) {
$data['images'] = array_splice($data['images'], 1000);
}
$builder = [
'url' => 'loc',
'location' => 'geo_location',
];
foreach ($data['images'] as $image) {
$images .= '<image:image>';
foreach ($image as $key => $element) {
$images .= sprintf('<image:%1$s>%2$s</image:%1$s>', $builder[$key] ?? $key, $element);
}
$images .= '</image:image>';
}
return sprintf(' <url><loc>%s</loc>%s</url>'."\n", $data['url'], $images);
}
/**
* Generate video line of sitemap.
*
* @param array<string, mixed> $data List of parameters
*/
private function generateVideoLine(array $data): string
{
$videos = '';
$builder = [
'thumbnail' => 'thumbnail_loc',
];
foreach ($data['video'] as $key => $video) {
$videos .= sprintf('<video:%1$s>%2$s</video:%1$s>', $builder[$key] ?? $key, $video);
}
return sprintf(' <url><loc>%s</loc><video:video>%s</video:video></url>'."\n", $data['url'], $videos);
}
/**
* Generate additional header with namespace adapted to the content.
*/
private function getHeaderByFlag(): string
{
$namespaces = [
'video' => 'xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"',
'image' => 'xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"',
];
$result = '';
foreach ($this->headers as $flag) {
$result .= ' '.$namespaces[$flag];
}
return $result;
}
private function closeSitemap(): void
{
fwrite($this->buffer, '</urlset>');
fclose($this->buffer);
}
}