Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bscheshirwork/88416dd46555d08fe57463624b613c56 to your computer and use it in GitHub Desktop.
Save bscheshirwork/88416dd46555d08fe57463624b613c56 to your computer and use it in GitHub Desktop.
nginx redirect generate. command for yii2
<?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