Created
April 17, 2019 09:53
-
-
Save bscheshirwork/88416dd46555d08fe57463624b613c56 to your computer and use it in GitHub Desktop.
nginx redirect generate. command for yii2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace console\controllers; | |
use Yii; | |
use yii\console\Controller; | |
use yii\console\ExitCode; | |
use yii\console\widgets\Table; | |
class RedirectController extends Controller | |
{ | |
const PROCESSED_DIR = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'runtime'; | |
/** | |
* Form redirect list from csv file | |
* @param string $fileName | |
* @return int | |
*/ | |
public function actionGenerate($fileName = '403.csv') | |
{ | |
$file = static::PROCESSED_DIR . DIRECTORY_SEPARATOR . $fileName; | |
$data = array_map('str_getcsv', file($file)); | |
if (!$data) { | |
return ExitCode::NOINPUT; | |
} | |
$table = new Table(); | |
$table->setHeaders([ | |
Yii::t('redirect', 'Old URL from file'), | |
Yii::t('redirect', 'New URL from file'), | |
]); | |
$tableRows = []; | |
if ($this->interactive) { | |
$consoleProgress = new \console\models\ConsoleProgress(['max' => count($data)]); | |
$consoleProgress->start(); | |
} | |
$result = ''; | |
$resultRows = []; | |
$template = 'map $request_uri $new_uri { | |
{rows} | |
} | |
'; | |
$rowTemplate = ' {oldShort} {newShort};'; | |
foreach ($data as $row) { | |
$oldShort = preg_filter('|http://www.old.ru|', '', $row[0]); | |
$newShort = preg_filter('|http://new:8080|', '', $row[1]); | |
$resultRows[] = strtr($rowTemplate, [ | |
'{oldShort}' => $oldShort, | |
'{newShort}' => $newShort, | |
]); | |
$tableRows[] = [ | |
$row[0], | |
$row[1], | |
]; | |
if (isset($consoleProgress)) { | |
$consoleProgress->advance(); | |
} | |
} | |
echo "\n" . $table->setRows($tableRows)->run(); | |
sort($resultRows); | |
$result = strtr($template, [ | |
'{rows}' => implode("\n", $resultRows), | |
]); | |
echo "\n" . $result . "\n"; | |
return ExitCode::OK; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment