-
Notifications
You must be signed in to change notification settings - Fork 988
/
m150511_124830_group_remove_language.php
70 lines (64 loc) · 2.54 KB
/
m150511_124830_group_remove_language.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
namespace ls\migrations;
use \CDbMigration;
class m150511_124830_group_remove_language extends CDbMigration
{
/**
* Describe the migration in this PHPDOC.
* Implement it below.
* @return boolean True if migration was a success.
*/
public function safeUp()
{
// We are removing languages from the answer table and moving it to the translation table.
$table = \ls\models\QuestionGroup::model()->tableName();
$this->dbConnection->schema->getTable($table, true);
$groups = \ls\models\QuestionGroup::model()->findAll();
$deleted = $created = 0;
/** @var \ls\models\QuestionGroup $group */
foreach ($groups as $group) {
$behaviorConfig = $group->behaviors()['translatable'];
// Get the base language
$baseLanguage = isset($behaviorConfig['translatable']['baseLanguage']) ? $behaviorConfig['translatable']['baseLanguage'] : 'en';
if ($baseLanguage instanceof \Closure) {
$baseLanguage = $baseLanguage($group);
}
if ($baseLanguage != $group->language) {
// Create translation if not base language.
$translation = new \ls\models\Translation();
$translation->language = $group->language;
$translation->model = 'Group'; // We have Single Table Inheritance so we use the base class.
$translation->model_id = $group->id;
foreach ($group->translatableAttributes as $attribute) {
$translation->$attribute = $group->$attribute;
}
try {
if ($translation->save()) {
$created++;
}
} catch (\Exception $e) {
$translation->setIsNewRecord(false);
if ($translation->save()) {
$created++;
}
}
if ($group->delete()) {
$deleted++;
}
}
}
if ($deleted !== $created) {
throw new \Exception("Upgrade did not create expected number of translations. Aborted to prevent data loss.");
}
// Create index for unique answer code (per question).
$this->dropColumn($table, 'language');
}
/**
* @return boolean True if migration was a success.
*/
public function safeDown()
{
echo "m150511_124830_group_remove_language does not support migration down.\\n";
return false;
}
}