/** * Building sitemat */ public function actionGenerate() { // Delete old files $this->deleteFiles(); // Get all models $activeModels = $this->_module->getModels(); $pages = []; foreach ($activeModels as $activeModel) { $pages = ArrayHelper::merge($pages, $activeModel->buildPages()); } $xmlData = Yii::$app->view->renderPhpFile($this->_module->viewPath . '/default/main-template.php', ['urls' => $pages]); if (file_put_contents($this->_pathMainFile, $xmlData)) { echo "{$this->_pathMainFile} - OK\n"; } }
/** * Create sitemap files * @return array */ public function buildPages() { /** @var \yii\db\ActiveRecord $owner */ $owner = $this->owner; $query = $owner::find(); $basePath = $this->module->getFilesPath(); preg_match('/([A-Za-z]+)$/', get_class($owner), $matchResult); $fileSuffix = strtolower($matchResult[0]); // Apply scopes if (is_callable($this->scope)) { call_user_func($this->scope, $query); } // Build data provider for separated on pages $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => $this->module->perPage, 'pageSizeLimit' => [10, 50000]]]); // Build pages $pages = []; $dataProvider->prepare(); $pageCount = $dataProvider->pagination->getPageCount(); for ($page = 0; $page < $pageCount; $page++) { $dataProvider->pagination->setPage($page); $dataProvider->prepare(true); // Processing one page $pageUrls = []; $n = 0; foreach ($dataProvider->getModels() as $model) { $urlData = call_user_func($this->dataClosure, $model); $pageUrls[$n]['loc'] = $urlData['loc']; $pageUrls[$n]['lastmod'] = $urlData['lastmod']; if (isset($urlData['changefreq'])) { $pageUrls[$n]['changefreq'] = $urlData['changefreq']; } elseif ($this->defaultChangefreq !== false) { $pageUrls[$n]['changefreq'] = $this->defaultChangefreq; } if (isset($urlData['priority'])) { $pageUrls[$n]['priority'] = $urlData['priority']; } elseif ($this->defaultPriority !== false) { $pageUrls[$n]['priority'] = $this->defaultPriority; } if (isset($urlData['news'])) { $pageUrls[$n]['news'] = $urlData['news']; } if (isset($urlData['images'])) { $pageUrls[$n]['images'] = $urlData['images']; } ++$n; } $xmlData = Yii::$app->view->renderPhpFile($this->module->viewPath . '/default/page-template.php', ['urls' => $pageUrls]); $fileUrl = "sitemap_files/{$fileSuffix}_{$page}.xml"; if (file_put_contents($basePath . '/' . $fileUrl, $xmlData)) { $pages[] = ['loc' => $fileUrl, 'lastmod' => time()]; echo "OK: {$basePath}/{$fileUrl}\n"; } } return $pages; }