Completed
Pull Request — master (#264)
by Robbie
13:29
created

MigrateTranslatableTask   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 150
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 22
lcom 1
cbo 1
dl 0
loc 150
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Translatable\Tasks;
4
5
use SilverStripe\CMS\Model\SiteTree;
6
use SilverStripe\Control\Director;
7
use SilverStripe\Core\ClassInfo;
8
use SilverStripe\Core\Convert;
9
use SilverStripe\Dev\BuildTask;
10
use SilverStripe\i18n\i18n;
11
use SilverStripe\ORM\DataObject;
12
use SilverStripe\ORM\DB;
13
use SilverStripe\Security\Permission;
14
use SilverStripe\Security\Security;
15
use SilverStripe\Translatable\Model\Translatable;
16
use SilverStripe\Versioned\Versioned;
17
18
/**
19
 * Migrates the old Translatable datamodel introduced in SilverStripe 2.1 to the new schema
20
 * introduced in SilverStripe 2.3.2.
21
 * Just works for {@link SiteTree} records and subclasses. If you have used the Translatable
22
 * extension on other {@link DataObject} subclasses before, this script won't migrate them automatically.
23
 *
24
 * <h2>Limitations</h2>
25
 *
26
 * - Information from the {@link Versioned} extension (e.g. in "SiteTree_versions" table)
27
 *   will be discarded for translated records.
28
 * - Custom translatable fields on your own {@link Page} class or subclasses thereof won't
29
 *   be migrated into the translation.
30
 * - 2.1-style subtags of a language (e.g. "en") will be automatically disambiguated to their full
31
 *   locale value (e.g. "en_US"), by the lookup defined in {@link i18n::get_locale_from_lang()}.
32
 * - Doesn't detect published translations when the script is run twice on the same data set
33
 *
34
 * <h2>Usage</h2>
35
 *
36
 * PLEASE BACK UP YOUR DATABASE BEFORE RUNNING THIS SCRIPT.
37
 *
38
 * Warning: Please run dev/build on your 2.2 database to update the schema before running this task.
39
 * The dev/build command will rename tables like "SiteTree_lang" to "_obsolete_SiteTree_lang".
40
 *
41
 * <h3>Commandline</h3>
42
 * Requires "sake" tool (see http://doc.silverstripe.com/?id=sake)
43
 * <example>
44
 * sake dev/tasks/MigrateTranslatableTask
45
 * </example>
46
 *
47
 * <h3>Browser</h3>
48
 * <example>
49
 * http://mydomain.com/dev/tasks/MigrateTranslatableTask
50
 * </example>
51
 *
52
 * @package translatable
53
 */
54
class MigrateTranslatableTask extends BuildTask
55
{
56
    protected $title = "Migrate Translatable Task";
57
58
    protected $description = "Migrates site translations from SilverStripe 2.1/2.2 to new database structure.";
59
60
    private static $segment = 'MigrateTranslatableTask';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $segment is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
61
62
    public function run($request)
63
    {
64
        $canAccess = (Director::isDev() || Director::is_cli() || Permission::check("ADMIN"));
65
        if (!$canAccess) {
66
            return Security::permissionFailure($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<SilverStripe\Transl...igrateTranslatableTask>, but the function expects a object<SilverStripe\Control\Controller>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
67
        }
68
69
        $ids = array();
70
71
        echo "#################################\n";
72
        echo "# Adding translation groups to existing records" . "\n";
73
        echo "#################################\n";
74
75
        $allSiteTreeIDs = DB::query('SELECT "ID" FROM "SiteTree"')->column();
76
        if ($allSiteTreeIDs) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $allSiteTreeIDs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
77
            foreach ($allSiteTreeIDs as $id) {
78
                $original = DataObject::get_by_id(SiteTree::class, $id);
79
                $existingGroupID = $original->getTranslationGroup();
80
                if (!$existingGroupID) {
81
                    $original->addTranslationGroup($original->ID);
82
                }
83
                $original->destroy();
84
                unset($original);
85
            }
86
        }
87
88
        DataObject::flush_and_destroy_cache();
89
90
        echo sprintf("Created translation groups for %d records\n", count($allSiteTreeIDs));
91
92
        foreach (array('Stage', 'Live') as $stage) {
93
            echo "\n\n#################################\n";
94
            echo "# Migrating stage $stage" . "\n";
95
            echo "#################################\n";
96
97
            $suffix = ($stage == 'Live') ? '_Live' : '';
98
99
            // First get all entries in SiteTree_lang
100
            // This should be all translated pages
101
            $trans = DB::query(sprintf('SELECT * FROM "_obsolete_SiteTree_lang%s"', $suffix));
102
103
            // Iterate over each translated pages
104
            foreach ($trans as $oldtrans) {
105
                $newLocale = i18n::get_locale_from_lang($oldtrans['Lang']);
0 ignored issues
show
Bug introduced by
The method get_locale_from_lang() does not exist on SilverStripe\i18n\i18n. Did you maybe mean get_locale()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
106
107
                echo sprintf(
108
                    "Migrating from %s to %s translation of '%s' (#%d)\n",
109
                    $oldtrans['Lang'],
110
                    $newLocale,
111
                    Convert::raw2xml($oldtrans['Title']),
112
                    $oldtrans['OriginalLangID']
113
                );
114
115
                // Get the untranslated page
116
117
                $original = Versioned::get_one_by_stage(
118
                    $oldtrans['ClassName'],
119
                    $stage,
120
                    '"SiteTree"."ID" = ' .  $oldtrans['OriginalLangID']
121
                );
122
123
                if (!$original) {
124
                    echo sprintf("Couldn't find original for #%d", $oldtrans['OriginalLangID']);
125
                    continue;
126
                }
127
128
                // write locale to $original
129
                $original->Locale = i18n::get_locale_from_lang(Translatable::default_lang());
0 ignored issues
show
Bug introduced by
The method default_lang() does not seem to exist on object<SilverStripe\Tran...ble\Model\Translatable>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method get_locale_from_lang() does not exist on SilverStripe\i18n\i18n. Did you maybe mean get_locale()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
130
                $original->writeToStage($stage);
131
132
                // Clone the original, and set it up as a translation
133
                $existingTrans = $original->getTranslation($newLocale, $stage);
134
135
                if ($existingTrans) {
136
                    echo sprintf(
137
                        "Found existing new-style translation for #%d. Already merged? Skipping.\n",
138
                        $oldtrans['OriginalLangID']
139
                    );
140
                    continue;
141
                }
142
143
                // Doesn't work with stage/live split
144
                //$newtrans = $original->createTranslation($newLocale);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
145
146
                $newtrans = $original->duplicate(false);
147
                $newtrans->OriginalID = $original->ID;
0 ignored issues
show
Bug introduced by
The property OriginalID does not seem to exist. Did you mean original?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
148
                // we have to "guess" a locale based on the language
149
                $newtrans->Locale = $newLocale;
150
                if ($stage == 'Live' && array_key_exists($original->ID, $ids)) {
151
                    $newtrans->ID = $ids[$original->ID];
152
                }
153
154
                // Look at each class in the ancestry, and see if there is a _lang table for it
155
                foreach (ClassInfo::ancestry($oldtrans['ClassName']) as $classname) {
156
                    $oldtransitem = false;
157
158
                    // If the class is SiteTree, we already have the DB record,
159
                    // else check for the table and get the record
160
                    if ($classname == SiteTree::class) {
161
                        $oldtransitem = $oldtrans;
162
                    } elseif (in_array(strtolower($classname) . '_lang', DB::tableList())) {
0 ignored issues
show
Bug introduced by
The method tableList() does not seem to exist on object<SilverStripe\ORM\DB>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
163
                        $oldtransitem = DB::query(sprintf(
164
                            'SELECT * FROM "_obsolete_%s_lang%s" WHERE "OriginalLangID" = %d AND "Lang" = \'%s\'',
165
                            $classname,
166
                            $suffix,
167
                            $original->ID,
168
                            $oldtrans['Lang']
169
                        ))->first();
170
                    }
171
172
                    // Copy each translated field into the new translation
173
                    if ($oldtransitem) {
174
                        foreach ($oldtransitem as $key => $value) {
175
                            if (!in_array($key, array('ID', 'OriginalLangID'))) {
176
                                $newtrans->$key = $value;
177
                            }
178
                        }
179
                    }
180
                }
181
182
                // Write the new translation to the database
183
                $sitelang = Translatable::get_current_locale();
184
                Translatable::set_current_locale($newtrans->Locale);
185
                $newtrans->writeToStage($stage);
186
                Translatable::set_current_locale($sitelang);
187
188
                $newtrans->addTranslationGroup($original->getTranslationGroup(), true);
189
190
191
                if ($stage == 'Stage') {
192
                    $ids[$original->ID] = $newtrans->ID;
193
                }
194
            }
195
        }
196
197
        echo "\n\n#################################\n";
198
        echo "Done!\n";
199
    }
200
}
201