Files
core/app/Http/Controllers/Sitemap.php

98 lines
2.4 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\CMS\Contracts\Repositories\Content;
use App\Http\Requests;
class Sitemap extends Controller
{
/**
* @var Content
*/
private $content;
/**
* Sitemap constructor.
*
* @param Content $content
*/
public function __construct(Content $content)
{
$this->content = $content;
}
/**
* Get sitemap for all content pages
*
* @return mixed
*/
public function getMap()
{
// load all public pages
$pages = $this->content->all();
// iterate over all pages and add tag for each of them
foreach ($pages as $page) {
// is this page a homepage? because of URL
if ($page->isHomepage) {
$route = route('page.index');
$priority = 1;
} else {
$route = route('page.content', ['url' => $page->url]);
$priority = 0.8;
}
// compute update frequency
$updateFrequency = $this->getUpdateFrequency($page->updated_at);
// add to all pages
\Sitemap::addTag($route, $page->updated_at, $updateFrequency, $priority);
}
// print sitemap
return \Sitemap::render();
}
/**
* Based on updatedAt compute "changefreq" for sitemap
*
* @param $updatedAt
*/
private function getUpdateFrequency($updatedAt)
{
// shortcuts for times
$day = 24 * 60 * 60;
$week = 7 * $day;
$month = 4 * $week;
$year = 12 * $month;
// change frequencies in format "name" => maximum age of last editation
$changeFrequencies = [
'always' => 300,
'hourly' => 3600,
'daily' => $day,
'weekly' => $week,
'monthly' => $month,
'yearly' => $year,
'never' => PHP_INT_MAX,
];
// get time difference
$timeDiffInMinutes = time() - strtotime($updatedAt);
// iterate over array with all change frequencies and break when time of edit is smaller than maximum time
do {
$changeFrequency = key($changeFrequencies);
$changeFreqMinTime = next($changeFrequencies);
} while ($timeDiffInMinutes > $changeFreqMinTime);
if ($changeFrequency != 'never') {
$changeFrequency = key($changeFrequencies);
}
return $changeFrequency;
}
}