forked from himiklab/yii2-sitemap-module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sitemap.php
85 lines (69 loc) · 2.09 KB
/
Sitemap.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
/**
* @link https://github.com/himiklab/yii2-sitemap-module
* @copyright Copyright (c) 2014 HimikLab
* @license http://opensource.org/licenses/MIT MIT
*/
namespace himiklab\sitemap;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\Module;
use yii\caching\Cache;
/**
* Yii2 module for automatically generating XML Sitemap.
*
* @author HimikLab
* @package himiklab\sitemap
*/
class Sitemap extends Module
{
public $controllerNamespace = 'himiklab\sitemap\controllers';
/** @var int */
public $cacheExpire = 86400;
/** @var Cache|string */
public $cacheProvider = 'cache';
/** @var string */
public $cacheKey = 'sitemap';
/** @var boolean Use php's gzip compressing. */
public $enableGzip = false;
/** @var array */
public $models = [];
/** @var array */
public $urls = [];
public function init()
{
parent::init();
if (is_string($this->cacheProvider)) {
$this->cacheProvider = Yii::$app->{$this->cacheProvider};
}
if (!$this->cacheProvider instanceof Cache) {
throw new InvalidConfigException('Invalid `cacheKey` parameter was specified.');
}
}
/**
* Build and cache a site map.
* @return string
* @throws \yii\base\InvalidConfigException
*/
public function buildSitemap()
{
$urls = $this->urls;
foreach ($this->models as $modelName) {
/** @var behaviors\SitemapBehavior $model */
if (is_array($modelName)) {
$model = new $modelName['class'];
if (isset($modelName['behaviors'])) {
$model->attachBehaviors($modelName['behaviors']);
}
} else {
$model = new $modelName;
}
$urls = array_merge($urls, $model->generateSiteMap());
}
$sitemapData = $this->createControllerByID('default')->renderPartial('index', [
'urls' => $urls
]);
$this->cacheProvider->set($this->cacheKey, $sitemapData, $this->cacheExpire);
return $sitemapData;
}
}