Skip to content

Instantly share code, notes, and snippets.

@Eseperio
Last active April 2, 2019 16:28
Show Gist options
  • Save Eseperio/cc29093002511872c0261f03b892fa34 to your computer and use it in GitHub Desktop.
Save Eseperio/cc29093002511872c0261f03b892fa34 to your computer and use it in GitHub Desktop.
This is an example of a migration to move translated messages from Yii php files to lajax yii2-translate
<?php
use lajax\translatemanager\models\LanguageSource;
use lajax\translatemanager\models\LanguageTranslate;
use yii\db\Migration;
/**
* Class m190402_151021_move_translations_to_db
*/
class m190402_151021_move_translations_to_db extends Migration
{
protected $tempTableName = 'gvp_translate';
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->delete(LanguageTranslate::tableName(), ['language' => 'es-ES']);
$files = glob(Yii::getAlias('@app/messages') . '/??/*.php');
foreach ($files as $file) {
$messages = include($file);
$category = pathinfo($file, PATHINFO_BASENAME);
$this->createTempTable();
$messages = array_filter($messages, function ($val) {
return !empty($val);
});
array_walk($messages, function (&$value, $key) use ($category) {
$value = ['es-ES', $value, $key];
});
$this->batchInsert($this->tempTableName, [
'language',
'translation',
'message'
], $messages);
$translationsTableName = LanguageTranslate::tableName();
$sourceTableName = LanguageSource::tableName();
$sql2 = <<<MYSQL
INSERT INTO {$translationsTableName} (SELECT a.id,t.language,t.translation FROM {$this->tempTableName} AS t INNER JOIN {$sourceTableName} a ON BINARY a.message= t.message)
MYSQL;
$this->execute($sql2);
$this->dropTable($this->tempTableName);
}
}
public function createTempTable()
{
$sql = <<<MYSQL
create temporary table {$this->tempTableName}
(
id int not null,
language varchar(5) not null,
translation text null,
message text null
)
MYSQL;
$this->execute($sql);
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
return true;
}
/*
// Use up()/down() to run migration code without a transaction.
public function up()
{
}
public function down()
{
echo "m190402_151021_move_translations_to_db cannot be reverted.\n";
return false;
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment