1 | <?php |
||
2 | /** |
||
3 | * Yii2 module for automatically generating robots.txt. |
||
4 | * |
||
5 | * @link https://github.com/himiklab/yii2-sitemap-module |
||
6 | * @author Serge Larin <[email protected]> |
||
7 | * @author HimikLab |
||
8 | * @copyright 2015 Assayer Pro Company |
||
9 | * @license http://opensource.org/licenses/MIT MIT |
||
10 | * |
||
11 | */ |
||
12 | namespace assayerpro\sitemap; |
||
13 | |||
14 | use Yii; |
||
15 | use yii\helpers\Url; |
||
16 | |||
17 | /** |
||
18 | * Yii2 module for automatically generating robots.txt. |
||
19 | * |
||
20 | * @author Serge Larin <[email protected]> |
||
21 | * @package assayerpro\sitemap |
||
22 | */ |
||
23 | class RobotsTxt extends \yii\base\Component |
||
24 | { |
||
25 | /** @var sting */ |
||
26 | public $host = ''; |
||
27 | /** @var string */ |
||
28 | public $sitemap = ''; |
||
29 | /** @var array */ |
||
30 | public $userAgent = []; |
||
31 | /** |
||
32 | * @inheritdoc |
||
33 | */ |
||
34 | 5 | public function init() |
|
35 | { |
||
36 | 5 | parent::init(); |
|
37 | 5 | if (empty($this->host)) { |
|
38 | 4 | if (Yii::$app->request->IsSecureConnection) { |
|
39 | 1 | $this->host = Yii::$app->request->hostInfo; |
|
40 | 1 | } else { |
|
41 | 3 | $this->host = Yii::$app->request->serverName; |
|
42 | } |
||
43 | 4 | } |
|
44 | 5 | } |
|
45 | /** |
||
46 | * render robots.txt |
||
47 | * |
||
48 | * @return string |
||
49 | */ |
||
50 | 5 | public function render() |
|
51 | { |
||
52 | 5 | $result = ""; |
|
53 | 5 | $params = []; |
|
54 | 5 | $params['Host'] = $this->host; |
|
55 | 5 | $params['Sitemap'] = $this->sitemap; |
|
56 | 5 | foreach (array_filter($params) as $key => $value) { |
|
57 | 5 | $result .= "$key: $value\n"; |
|
58 | 5 | } |
|
59 | 5 | foreach ($this->userAgent as $userAgent => $value) { |
|
60 | 1 | $result .= "User-agent: $userAgent\n"; |
|
61 | 1 | foreach ($value as $permission => $urls) { |
|
62 | 1 | foreach ($urls as $url) { |
|
63 | 1 | $url = Url::to($url); |
|
64 | 1 | $result .= "$permission: $url\n"; |
|
65 | 1 | } |
|
66 | 1 | } |
|
67 | 5 | } |
|
68 | 5 | return $result; |
|
69 | |||
70 | } |
||
71 | } |
||
72 |