diff --git a/services.yaml b/services.yaml index a9903a4..e5a22be 100644 --- a/services.yaml +++ b/services.yaml @@ -1,5 +1,6 @@ imports: - { resource: src/Repository/services.yaml } + - { resource: src/Service/services.yaml } services: _defaults: diff --git a/src/Service/XmlGenerator.php b/src/Service/XmlGenerator.php new file mode 100644 index 0000000..aef22d7 --- /dev/null +++ b/src/Service/XmlGenerator.php @@ -0,0 +1,49 @@ +wrap($url->getLocation(), "loc"), + $this->wrap($url->getLastModified(), "lastmod"), + $this->wrap($url->getChangeFrequency(), "changefreq"), + $this->wrap((string)$url->getPriority(), "priority"), + ]; + + return $this->wrap(implode("", $attributes), "url"); + } + + protected function wrap(string $data, string $tag, array $tagAttributes = []): string + { + $attributes = ''; + foreach ($tagAttributes as $key => $attributeValue) { + $attributes .= " {$key}=\"{$attributeValue}\""; + } + + return "<{$tag}{$attributes}>" . $data . ""; + } + + public function generateSitemapDocument(iterable $items): string + { + $document = ''; + + $urlBlocks = []; + foreach ($items as $oneItem) { + $urlBlocks[] = $this->generateUrlItem($oneItem); + } + + return $document + . $this->wrap( + implode("", $urlBlocks), + "urlset", + [ + "xmlns" => "http://www.sitemaps.org/schemas/sitemap/0.9" + ] + ); + } +} diff --git a/src/Service/XmlGeneratorInterface.php b/src/Service/XmlGeneratorInterface.php new file mode 100644 index 0000000..21f647b --- /dev/null +++ b/src/Service/XmlGeneratorInterface.php @@ -0,0 +1,8 @@ +createConfiguredMock(UrlInterface::class, [ + 'getLocation' => 'someLocation', + 'getLastModified' => 'lastModifiedDate', + 'getChangeFrequency' => 'someFrequency', + 'getPriority' => 0.6, + ]); + + $expectation = implode("", [ + "", + "someLocation", + "lastModifiedDate", + "someFrequency", + "0.6", + "", + ]); + + $sut = $this->createPartialMock(XmlGenerator::class, []); + $this->assertSame($expectation, $sut->generateUrlItem($urlStub)); + } + + public function testGenerateSitemapContent(): void + { + $sut = $this->createPartialMock(XmlGenerator::class, ['generateUrlItem']); + $sut->expects($this->exactly(3))->method('generateUrlItem')->willReturn("ItemContent"); + + $expectation = implode("", [ + '', + '', + 'ItemContent', + 'ItemContent', + 'ItemContent', + '' + ]); + + $items = [ + $this->createStub(UrlInterface::class), + $this->createStub(UrlInterface::class), + $this->createStub(UrlInterface::class), + ]; + + $this->assertSame($expectation, $sut->generateSitemapDocument($items)); + } +}