|
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(private readonly ProductRepository $productRepository, private readonly NewsRepository $newsRepository, private readonly string $baseUrl, private readonly array $sitemapStaticUrls) |
|
18
|
|
|
{ |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
|
22
|
|
|
{ |
|
23
|
|
|
$sitemap = $this->getSitemap(); |
|
24
|
|
|
$response = new XmlResponse($sitemap); |
|
25
|
|
|
|
|
26
|
|
|
return $response; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
private function getSitemap(): string |
|
30
|
|
|
{ |
|
31
|
|
|
$document = new DOMDocument('1.0', 'UTF-8'); |
|
32
|
|
|
$document->formatOutput = true; |
|
33
|
|
|
$urlset = $document->createElement('urlset'); |
|
34
|
|
|
$document->appendChild($urlset); |
|
35
|
|
|
$urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); |
|
36
|
|
|
|
|
37
|
|
|
$this->addUrl($document, $urlset, '/'); |
|
38
|
|
|
|
|
39
|
|
|
foreach ($this->sitemapStaticUrls as $url) { |
|
40
|
|
|
$this->addUrl($document, $urlset, $url); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$products = $this->productRepository->getIds(); |
|
44
|
|
|
foreach ($products as $product) { |
|
45
|
|
|
if ($product['reviewNumber']) { |
|
46
|
|
|
$this->addUrl($document, $urlset, '/larevuedurable/numero/' . $product['id']); |
|
47
|
|
|
} else { |
|
48
|
|
|
$this->addUrl($document, $urlset, '/larevuedurable/article/' . $product['id']); |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
$news = $this->newsRepository->getIds(); |
|
53
|
|
|
foreach ($news as $new) { |
|
54
|
|
|
$this->addUrl($document, $urlset, '/actualite/' . $new['id']); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
$result = $document->saveXml(); |
|
58
|
|
|
|
|
59
|
|
|
return $result; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
private function addUrl(DOMDocument $document, DOMNode $urlset, string $urlValue): void |
|
63
|
|
|
{ |
|
64
|
|
|
$url = $document->createElement('url'); |
|
65
|
|
|
$urlset->appendChild($url); |
|
66
|
|
|
$loc = $document->createElement('loc', $this->baseUrl . htmlspecialchars($urlValue)); |
|
67
|
|
|
$url->appendChild($loc); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|