Skip to content

Commit

Permalink
Refactory Sitemap creator
Browse files Browse the repository at this point in the history
  • Loading branch information
stupidkitty committed Jan 22, 2020
1 parent 343fbb5 commit 97fffa6
Show file tree
Hide file tree
Showing 5 changed files with 151 additions and 66 deletions.
6 changes: 4 additions & 2 deletions src/Command/SitemapController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use Yii;
use yii\console\Controller;
use SK\SeoModule\Sitemap\SitemapGenerator;
use SK\SeoModule\Sitemap\SitemapBuilder;

class SitemapController extends Controller
{
Expand All @@ -13,7 +13,9 @@ class SitemapController extends Controller
*/
public function actionCreate()
{
$sitemapGenerator = Yii::$container->get(SitemapGenerator::class);
$sitemapBuilder = Yii::$container->get(SitemapBuilder::class);

$sitemapGenerator = $sitemapBuilder->build();
$sitemapGenerator->generate();
}

Expand Down
6 changes: 4 additions & 2 deletions src/CronJob/SitemapCreate.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@
namespace SK\SeoModule\CronJob;

use Yii;
use SK\SeoModule\Sitemap\SitemapGenerator;
use SK\SeoModule\Sitemap\SitemapBuilder;
use SK\CronModule\Handler\HandlerInterface;

class SitemapCreate implements HandlerInterface
{
public function run()
{
$sitemapGenerator = Yii::$container->get(SitemapGenerator::class);
$sitemapBuilder = Yii::$container->get(SitemapBuilder::class);

$sitemapGenerator = $sitemapBuilder->build();
$sitemapGenerator->generate();
}
}
75 changes: 75 additions & 0 deletions src/Sitemap/SitemapBuilder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php
namespace SK\SeoModule\Sitemap;

use Yii;
use yii\helpers\FileHelper;
use RS\Component\Core\Settings\SettingsInterface;

class SitemapBuilder
{
public $generators = [];
public $baseSitemapUrl;
public $outputDirectory = '@app/web/sitemap';

private $settings;

public function __construct(SettingsInterface $settings)
{
$this->settings = $settings;
}

public function build()
{
$sitemapGenerator = $this->buildGenerator();

if (empty($this->baseSitemapUrl)) {
$siteUrl = rtrim($this->settings->get('site_url', 'https://site.com/'), '/');

$sitemapGenerator->setBaseSitemapUrl("{$siteUrl}/sitemap/");
} else {
$sitemapGenerator->setBaseSitemapUrl($this->baseSitemapUrl);
}

$outputDirectory = Yii::getAlias($this->outputDirectory);

if (!is_dir($outputDirectory)) {
FileHelper::createDirectory($outputDirectory, 0755);
}

$sitemapGenerator->setOutputDirectory($outputDirectory);

foreach ($this->generators as $generatorConfig) {
$generator = Yii::createObject($generatorConfig);

$sitemapGenerator->addGenerator($generator);
}

return $sitemapGenerator;
}

public function buildGenerator()
{
return new SitemapGenerator;
}

public function addGenerator($generator): self
{
$this->generators[] = $generator;

return $this;
}

public function setBaseSitemapUrl(string $baseSitemapUrl): self
{
$this->baseSitemapUrl = $baseSitemapUrl;

return $this;
}

public function setOutputDirectory(string $outputDirectory = '@app/web'): self
{
$this->outputDirectory = $outputDirectory;

return $this;
}
}
119 changes: 57 additions & 62 deletions src/Sitemap/SitemapGenerator.php
Original file line number Diff line number Diff line change
@@ -1,110 +1,105 @@
<?php
namespace SK\SeoModule\Sitemap;

use Yii;
use yii\base\Event;
use samdark\sitemap\Index;
use yii\helpers\FileHelper;
use samdark\sitemap\Sitemap;
use RS\Component\Core\Settings\SettingsInterface;

/**
* https://github.com/samdark/sitemap
*/
class SitemapGenerator
{
public $baseSitemapUrl;
public $baseDirectory;
private $baseSitemapUrl;
private $outputDirectory;

private $urlManager;
private $index;
private $sitemapCollection = [];
private $generators = [];

const EVENT_BEFORE_GENERATE = 'beforeGenerate';

public function __construct(SettingsInterface $settings)
/**
* Генерация карт сайта.
*/
public function generate()
{
$siteUrl = $settings->get('site_url');
$index = new Index("{$this->outputDirectory}/index.xml");

$this->urlManager = Yii::$app->urlManager;
$this->urlManager->setScriptUrl('/web/index.php');
$this->urlManager->setHostInfo($siteUrl);
$createdSitemaps = [];
foreach ($this->generators as $generator) {
$urls = $this->handle($generator);

$this->baseSitemapUrl = "{$siteUrl}/sitemap/";
$this->baseDirectory = Yii::getAlias('@root/web/sitemap');
$createdSitemaps = \array_merge($createdSitemaps, $urls);
}

if (!is_dir($this->baseDirectory)) {
FileHelper::CreateDirectory($this->baseDirectory, 0755);
foreach ($createdSitemaps as $url) {
$index->addSitemap($url);
}

$indexFilepath = $this->baseDirectory . '/index.xml';
$this->index = new Index($indexFilepath);
$index->write();
}

/**
* Генерация карт сайта.
* Создание сайт мапы из коллекции тасков.
*
* @param callable $callback Функция генерации урлов.
* @param string $filename Название файла, в который будут записаны урлы.
* @return array Список сгенерированных файлов.
*/
public function generate()
private function handle(SitemapHandlerInterface $generator): array
{
Event::trigger(static::class, static::EVENT_BEFORE_GENERATE, new Event(['sender' => $this]));
try {
$filename = $generator->getFilename();
$filepath = "{$this->outputDirectory}/{$filename}";
$sitemap = new Sitemap($filepath);

foreach ($this->sitemapCollection as $row) { //['callback' => $callback, 'filename' => $filename]
$this->handle($row['callback'], $row['filename']);
}
$generator->create($sitemap);

$sitemap->write();

$this->index->write();
return $sitemap->getSitemapUrls($this->baseSitemapUrl);
} catch (\Throwable $e) {
echo $e->getMessage() . "\n";

return [];
}
}

/**
* Добавление обработчиков для генерации карт.
* Устанавливает массив генераторов карт сайта.
*
* @param callable $callback Функция генерации урлов.
* @param string $filename Название файла, в который будут записаны урлы.
* @param array $generators
* @return self
*/
public function addSitemap(callable $callback, $filename = '')
public function setGenerators(SitemapHandlerInterface ...$generators): self
{
if ('' === $filename) {
$sitemapNum = count($this->sitemapCollection) + 1;
$filename = "sitemap{$sitemapNum}.xml";
}
$this->generators = $generators;

$this->sitemapCollection[] = [
'filename' => $filename,
'callback' => $callback,
];
return $this;
}

/**
* Создание сайт мапы из коллекции тасков.
* Добавляет генератор карты мапы.
*
* @param callable $callback Функция генерации урлов.
* @param string $filename Название файла, в который будут записаны урлы.
* @param SitemapHandlerInterface $generators
* @return self
*/
private function handle(callable $callback, $filename)
public function addGenerator(SitemapHandlerInterface $generator): self
{
$filepath = "{$this->baseDirectory}/{$filename}";
$sitemap = new Sitemap($filepath);
$this->generators[] = $generator;

$callback($sitemap, $this->urlManager);
return $this;
}

$sitemap->write();
public function setBaseSitemapUrl(string $baseSitemapUrl): self
{
$baseSitemapUrl = rtrim($baseSitemapUrl, '/') . '/';
$this->baseSitemapUrl = $baseSitemapUrl;

$sitemapFileUrls = $sitemap->getSitemapUrls($this->baseSitemapUrl);
$this->addSitemapToIndex($sitemapFileUrls);
return $this;
}

/**
* Добавление сгенерированных файлов в индексный файл.
*
* @param array $sitemapFileUrls Коллекция урлов сгенерированных карт сайта.
*/
private function addSitemapToIndex($sitemapFileUrls)
public function setOutputDirectory(string $outputDirectory = '@app/web'): self
{
if (empty($sitemapFileUrls))
return;
$outputDirectory = rtrim($outputDirectory, '/') . '/';
$this->outputDirectory = $outputDirectory;

foreach ($sitemapFileUrls as $sitemapUrl) {
$this->index->addSitemap($sitemapUrl);
}
return $this;
}
}
11 changes: 11 additions & 0 deletions src/Sitemap/SitemapHandlerInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php
namespace SK\SeoModule\Sitemap;

use samdark\sitemap\Sitemap;

interface SitemapHandlerInterface
{
public function getFilename(): string;

public function create(Sitemap $sitemap);
}

0 comments on commit 97fffa6

Please sign in to comment.