From 34dbf3455f0d7aef3dd71d8a669a8ac01c5f89e6 Mon Sep 17 00:00:00 2001 From: Johannes Berdin Date: Fri, 9 Dec 2016 10:43:05 +0100 Subject: [PATCH] Added sitemap generation --- src/SiteBuilder.php | 17 +++++++++ src/SitemapBuilder.php | 78 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 src/SitemapBuilder.php diff --git a/src/SiteBuilder.php b/src/SiteBuilder.php index dcd2cc4..899cc6d 100644 --- a/src/SiteBuilder.php +++ b/src/SiteBuilder.php @@ -124,6 +124,7 @@ public function build() $this->handleBlogPostsFiles($blogPostsFiles); $this->buildBlogPagination(); $this->buildRSSFeed(); + $this->buildSitemap(); } } @@ -267,4 +268,20 @@ private function buildRSSFeed() $builder->build(); } + + /** + * Build the blog sitemap. + * + * @return void + */ + private function buildSitemap() + { + $builder = new SitemapBuilder( + $this->filesystem, + $this->viewFactory, + $this->viewsData + ); + + $builder->build(); + } } diff --git a/src/SitemapBuilder.php b/src/SitemapBuilder.php new file mode 100644 index 0000000..c0ce90a --- /dev/null +++ b/src/SitemapBuilder.php @@ -0,0 +1,78 @@ +filesystem = $filesystem; + $this->viewFactory = $viewFactory; + $this->viewsData = $viewsData; + } + + /** + * Build blog Sitemap file. + * + * @return void + */ + public function build() + { + if (! $view = $this->getSitemapView()) { + return; + } + + // Filter out some compiled sites for generating the sitemap. + $files = array_filter($this->filesystem->allFiles(KATANA_PUBLIC_DIR), function (SplFileInfo $file) { + $path = $file->getRelativePathName(); + return Str::endsWith($path, '.html') && !Str::startsWith($path, 'blog-page') && !Str::startsWith($path, 'sitemap') && !Str::startsWith($path, 'feed'); + }); + + // Only get the relative path of the files. + $sites = array_map(function($site) { + return str_replace('index.html', '', $site->getRelativePathName()); + }, $files); + + $pageContent = $this->viewFactory->make($view, $this->viewsData + ['sites' => (array)$sites])->render(); + + $this->filesystem->put( + sprintf('%s/%s', KATANA_PUBLIC_DIR, 'sitemap.xml'), + $pageContent + ); + } + + /** + * Get the name of the view to be used for generating the Sitemap. + * + * @return mixed + * @throws \Exception + */ + private function getSitemapView() + { + if (! isset($this->viewsData['sitemapView']) || ! @$this->viewsData['sitemapView']) { + return null; + } + + if (! $this->viewFactory->exists($this->viewsData['sitemapView'])) { + throw new \Exception(sprintf('The "%s" view is not found. Make sure the rssFeedView configuration key is correct.', $this->viewsData['rssFeedView'])); + } + + return $this->viewsData['sitemapView']; + } +}