MigrateToDocumentSetsTask   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 243
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 8
dl 0
loc 243
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 18 2
A isDryrun() 0 4 1
A createDefaultSet() 0 20 4
B reassignDocuments() 0 36 6
A addDefaultDocumentSet() 0 14 2
A addDocumentToSet() 0 9 2
A outputHeader() 0 8 2
A outputResults() 0 9 2
A addResult() 0 8 2
A output() 0 9 2
A isCli() 0 4 1
1
<?php
2
/**
3
 * This build task helps to migrate DMS data structures from DMS 1.x to 2.x which introduces document sets.
4
 *
5
 * See the "document-sets.md" migration guide for more information and use examples.
6
 */
7
class MigrateToDocumentSetsTask extends BuildTask
8
{
9
    protected $title = 'DMS 2.0 Migration Tool';
10
11
    protected $description = 'Migration tool for upgrading from DMS 1.x to 2.x. Add "action=create-default-document-set" to create a default set. "reassign-documents" to reassign legacy document relations. "dryrun=1" to show changes without writing.';
12
13
    /**
14
     * The valid actions that this task can perform (and the method that does them as the key)
15
     * @var array
16
     */
17
    protected $validActions = array(
18
        'createDefaultSet' => 'create-default-document-set',
19
        'reassignDocuments' => 'reassign-documents'
20
    );
21
22
    /**
23
     * @var SS_HTTPRequest
24
     */
25
    protected $request;
26
27
    /**
28
     * Holds number of pages/sets/documents processed for output at the end. Example:
29
     *
30
     * <code>
31
     * array(
32
     *     'total-pages' => 0,
33
     *     'pages-updated' => 0
34
     * )
35
     * </code>
36
     *
37
     * The individual action methods will update these metrics as required
38
     *
39
     * @var array
40
     */
41
    protected $results = array();
42
43
    public function run($request)
44
    {
45
        $this->request = $request;
46
47
        $action = $request->getVar('action');
48
        if (!in_array($action, $this->validActions)) {
49
            $this->output(
50
                'Error! Specified action is not valid. Valid actions are: ' . implode(', ', $this->validActions)
51
            );
52
            $this->output('You can add "dryrun=1" to enable dryrun mode where no changes will be written to the DB.');
53
            return;
54
        }
55
56
        $this->outputHeader();
57
        $action = array_search($action, $this->validActions);
58
        $this->$action();
59
        $this->outputResults();
60
    }
61
62
    /**
63
     * Returns whether dryrun mode is enabled ("dryrun=1")
64
     *
65
     * @return bool
66
     */
67
    public function isDryrun()
68
    {
69
        return (bool) $this->request->getVar('dryrun') == 1;
70
    }
71
72
    /**
73
     * Creates a default document set for any valid page that doesn't have one
74
     *
75
     * @return $this
76
     */
77
    protected function createDefaultSet()
78
    {
79
        $pages = SiteTree::get();
80
        foreach ($pages as $page) {
81
            // Only handle valid page types
82
            if (!$page->config()->get('documents_enabled')) {
83
                $this->addResult('Skipped: documents disabled');
84
                continue;
85
            }
86
87
            if ($page->DocumentSets()->count()) {
88
                // Don't add a set if it already has one
89
                $this->addResult('Skipped: already has a set');
90
                continue;
91
            }
92
            $this->addDefaultDocumentSet($page);
93
            $this->addResult('Default document set added');
94
        }
95
        return $this;
96
    }
97
98
    /**
99
     * Reassign documents to the default document set, where they'd previously have been assigned to pages
100
     *
101
     * @return $this
102
     */
103
    protected function reassignDocuments()
104
    {
105
        $countCheck = SQLSelect::create('*', 'DMSDocument_Pages');
106
        if (!$countCheck->count()) {
107
            $this->output('There was no data to migrate. Finishing.');
108
            return $this;
109
        }
110
111
        $query = SQLSelect::create(array('DMSDocumentID', 'SiteTreeID'), 'DMSDocument_Pages');
112
        $result = $query->execute();
113
114
        foreach ($result as $row) {
115
            $document = DMSDocument::get()->byId($row['DMSDocumentID']);
116
            if (!$document) {
117
                $this->addResult('Skipped: document does not exist');
118
                continue;
119
            }
120
121
            $page = SiteTree::get()->byId($row['SiteTreeID']);
122
            if (!$page) {
123
                $this->addResult('Skipped: page does not exist');
124
                continue;
125
            }
126
127
            // Don't try and process pages that don't have a document set. This should be created by the first
128
            // action step in this build task, so shouldn't occur if run in correct order.
129
            if (!$page->DocumentSets()->count()) {
130
                $this->addResult('Skipped: no default document set');
131
                continue;
132
            }
133
            $this->addDocumentToSet($document, $page->DocumentSets()->first());
0 ignored issues
show
Compatibility introduced by
$document of type object<DataObject> is not a sub-type of object<DMSDocument>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
134
            $this->addResult('Reassigned to document set');
135
        }
136
137
        return $this;
138
    }
139
140
    /**
141
     * Create a "default" document set and add it to the given Page via the ORM relationship added by
142
     * {@link DMSSiteTreeExtension}
143
     *
144
     * @param  SiteTree $page
145
     * @return $this
146
     */
147
    protected function addDefaultDocumentSet(SiteTree $page)
148
    {
149
        if ($this->isDryrun()) {
150
            return $this;
151
        }
152
153
        $set = DMSDocumentSet::create();
154
        $set->Title = 'Default';
155
        $set->write();
156
157
        $page->DocumentSets()->add($set);
158
159
        return $this;
160
    }
161
162
    /**
163
     * Add the given document to the given document set
164
     *
165
     * @param  DMSDocument $document
166
     * @param  DMSDocumentSet $set
167
     * @return $this
168
     */
169
    protected function addDocumentToSet(DMSDocument $document, DMSDocumentSet $set)
170
    {
171
        if ($this->isDryrun()) {
172
            return $this;
173
        }
174
175
        $set->Documents()->add($document);
0 ignored issues
show
Bug introduced by
The method Documents() does not exist on DMSDocumentSet. Did you maybe mean getDocuments()?

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...
176
        return $this;
177
    }
178
179
    /**
180
     * Output a header info line
181
     *
182
     * @return $this
183
     */
184
    protected function outputHeader()
185
    {
186
        $this->output('Migrating DMS data to 2.x for document sets');
187
        if ($this->isDryrun()) {
188
            $this->output('NOTE: Dryrun mode enabled. No changes will be written.');
189
        }
190
        return $this;
191
    }
192
193
    /**
194
     * Output a "finished" notice and the results of what was done
195
     *
196
     * @return $this
197
     */
198
    protected function outputResults()
199
    {
200
        $this->output();
201
        $this->output('Finished:');
202
        foreach ($this->results as $metric => $count) {
203
            $this->output('+ ' . $metric . ': ' . $count);
204
        }
205
        return $this;
206
    }
207
208
    /**
209
     * Add the $increment to the result key identified by $key
210
     *
211
     * @param  string $key
212
     * @param  int    $increment
213
     * @return $this
214
     */
215
    protected function addResult($key, $increment = 1)
216
    {
217
        if (!array_key_exists($key, $this->results)) {
218
            $this->results[$key] = 0;
219
        }
220
        $this->results[$key] += $increment;
221
        return $this;
222
    }
223
224
    /**
225
     * Outputs a message formatted either for CLI or browser output
226
     *
227
     * @param  string $message
228
     * @return $this
229
     */
230
    public function output($message = '')
231
    {
232
        if ($this->isCli()) {
233
            echo $message, PHP_EOL;
234
        } else {
235
            echo $message . '<br />';
236
        }
237
        return $this;
238
    }
239
240
    /**
241
     * Returns whether the task is called via CLI or not
242
     *
243
     * @return bool
244
     */
245
    protected function isCli()
246
    {
247
        return Director::is_cli();
248
    }
249
}
250