1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Application\Handler; |
6
|
|
|
|
7
|
|
|
use Application\Repository\NewsRepository; |
8
|
|
|
use Application\Repository\ProductRepository; |
9
|
|
|
use DOMDocument; |
10
|
|
|
use DOMNode; |
11
|
|
|
use Laminas\Diactoros\Response\XmlResponse; |
12
|
|
|
use Psr\Http\Message\ResponseInterface; |
13
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
14
|
|
|
|
15
|
|
|
class SitemapHandler implements \Psr\Http\Server\RequestHandlerInterface |
16
|
|
|
{ |
17
|
|
|
public function __construct( |
18
|
|
|
private readonly ProductRepository $productRepository, |
19
|
|
|
private readonly NewsRepository $newsRepository, |
20
|
|
|
private readonly string $baseUrl, |
21
|
|
|
private readonly array $sitemapStaticUrls, |
22
|
|
|
) {} |
23
|
|
|
|
24
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
25
|
|
|
{ |
26
|
|
|
$sitemap = $this->getSitemap(); |
27
|
|
|
$response = new XmlResponse($sitemap); |
28
|
|
|
|
29
|
|
|
return $response; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
private function getSitemap(): string |
33
|
|
|
{ |
34
|
|
|
$document = new DOMDocument('1.0', 'UTF-8'); |
35
|
|
|
$document->formatOutput = true; |
36
|
|
|
$urlset = $document->createElement('urlset'); |
37
|
|
|
$document->appendChild($urlset); |
38
|
|
|
$urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); |
39
|
|
|
|
40
|
|
|
$this->addUrl($document, $urlset, '/'); |
41
|
|
|
|
42
|
|
|
foreach ($this->sitemapStaticUrls as $url) { |
43
|
|
|
$this->addUrl($document, $urlset, $url); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$products = $this->productRepository->getIds(); |
47
|
|
|
foreach ($products as $product) { |
48
|
|
|
if ($product['reviewNumber']) { |
49
|
|
|
$this->addUrl($document, $urlset, '/larevuedurable/numero/' . $product['id']); |
50
|
|
|
} else { |
51
|
|
|
$this->addUrl($document, $urlset, '/larevuedurable/article/' . $product['id']); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$news = $this->newsRepository->getIds(); |
56
|
|
|
foreach ($news as $new) { |
57
|
|
|
$this->addUrl($document, $urlset, '/actualite/' . $new['id']); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$result = $document->saveXml(); |
61
|
|
|
|
62
|
|
|
return $result; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
private function addUrl(DOMDocument $document, DOMNode $urlset, string $urlValue): void |
66
|
|
|
{ |
67
|
|
|
$url = $document->createElement('url'); |
68
|
|
|
$urlset->appendChild($url); |
69
|
|
|
$loc = $document->createElement('loc', $this->baseUrl . htmlspecialchars($urlValue)); |
70
|
|
|
$url->appendChild($loc); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|