Total Complexity | 89 |
Total Lines | 468 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like DatabaseAdmin often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use DatabaseAdmin, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
25 | class DatabaseAdmin extends Controller |
||
26 | { |
||
27 | |||
28 | /// SECURITY /// |
||
29 | private static $allowed_actions = array( |
||
|
|||
30 | 'index', |
||
31 | 'build', |
||
32 | 'cleanup', |
||
33 | 'import' |
||
34 | ); |
||
35 | |||
36 | /** |
||
37 | * Obsolete classname values that should be remapped in dev/build |
||
38 | */ |
||
39 | private static $classname_value_remapping = [ |
||
40 | 'File' => 'SilverStripe\\Assets\\File', |
||
41 | 'Image' => 'SilverStripe\\Assets\\Image', |
||
42 | 'Folder' => 'SilverStripe\\Assets\\Folder', |
||
43 | 'Group' => 'SilverStripe\\Security\\Group', |
||
44 | 'LoginAttempt' => 'SilverStripe\\Security\\LoginAttempt', |
||
45 | 'Member' => 'SilverStripe\\Security\\Member', |
||
46 | 'MemberPassword' => 'SilverStripe\\Security\\MemberPassword', |
||
47 | 'Permission' => 'SilverStripe\\Security\\Permission', |
||
48 | 'PermissionRole' => 'SilverStripe\\Security\\PermissionRole', |
||
49 | 'PermissionRoleCode' => 'SilverStripe\\Security\\PermissionRoleCode', |
||
50 | 'RememberLoginHash' => 'SilverStripe\\Security\\RememberLoginHash', |
||
51 | ]; |
||
52 | |||
53 | protected function init() |
||
54 | { |
||
55 | parent::init(); |
||
56 | |||
57 | // We allow access to this controller regardless of live-status or ADMIN permission only |
||
58 | // if on CLI or with the database not ready. The latter makes it less errorprone to do an |
||
59 | // initial schema build without requiring a default-admin login. |
||
60 | // Access to this controller is always allowed in "dev-mode", or of the user is ADMIN. |
||
61 | $allowAllCLI = DevelopmentAdmin::config()->get('allow_all_cli'); |
||
62 | $canAccess = ( |
||
63 | Director::isDev() |
||
64 | || !Security::database_is_ready() |
||
65 | // We need to ensure that DevelopmentAdminTest can simulate permission failures when running |
||
66 | // "dev/tests" from CLI. |
||
67 | || (Director::is_cli() && $allowAllCLI) |
||
68 | || Permission::check("ADMIN") |
||
69 | ); |
||
70 | if (!$canAccess) { |
||
71 | Security::permissionFailure( |
||
72 | $this, |
||
73 | "This page is secured and you need administrator rights to access it. " . |
||
74 | "Enter your credentials below and we will send you right along." |
||
75 | ); |
||
76 | } |
||
77 | } |
||
78 | |||
79 | /** |
||
80 | * Get the data classes, grouped by their root class |
||
81 | * |
||
82 | * @return array Array of data classes, grouped by their root class |
||
83 | */ |
||
84 | public function groupedDataClasses() |
||
85 | { |
||
86 | // Get all root data objects |
||
87 | $allClasses = get_declared_classes(); |
||
88 | $rootClasses = []; |
||
89 | foreach ($allClasses as $class) { |
||
90 | if (get_parent_class($class) == DataObject::class) { |
||
91 | $rootClasses[$class] = array(); |
||
92 | } |
||
93 | } |
||
94 | |||
95 | // Assign every other data object one of those |
||
96 | foreach ($allClasses as $class) { |
||
97 | if (!isset($rootClasses[$class]) && is_subclass_of($class, DataObject::class)) { |
||
98 | foreach ($rootClasses as $rootClass => $dummy) { |
||
99 | if (is_subclass_of($class, $rootClass)) { |
||
100 | $rootClasses[$rootClass][] = $class; |
||
101 | break; |
||
102 | } |
||
103 | } |
||
104 | } |
||
105 | } |
||
106 | return $rootClasses; |
||
107 | } |
||
108 | |||
109 | |||
110 | /** |
||
111 | * When we're called as /dev/build, that's actually the index. Do the same |
||
112 | * as /dev/build/build. |
||
113 | */ |
||
114 | public function index() |
||
115 | { |
||
116 | return $this->build(); |
||
117 | } |
||
118 | |||
119 | /** |
||
120 | * Updates the database schema, creating tables & fields as necessary. |
||
121 | */ |
||
122 | public function build() |
||
123 | { |
||
124 | // The default time limit of 30 seconds is normally not enough |
||
125 | Environment::increaseTimeLimitTo(600); |
||
126 | |||
127 | // If this code is being run outside of a dev/build or without a ?flush query string param, |
||
128 | // the class manifest hasn't been flushed, so do it here |
||
129 | $request = $this->getRequest(); |
||
130 | if (!array_key_exists('flush', $request->getVars()) && strpos($request->getURL(), 'dev/build') !== 0) { |
||
131 | ClassLoader::inst()->getManifest()->regenerate(false); |
||
132 | } |
||
133 | |||
134 | $url = $this->getReturnURL(); |
||
135 | if ($url) { |
||
136 | echo "<p>Setting up the database; you will be returned to your site shortly....</p>"; |
||
137 | $this->doBuild(true); |
||
138 | echo "<p>Done!</p>"; |
||
139 | $this->redirect($url); |
||
140 | } else { |
||
141 | $quiet = $this->request->requestVar('quiet') !== null; |
||
142 | $fromInstaller = $this->request->requestVar('from_installer') !== null; |
||
143 | $populate = $this->request->requestVar('dont_populate') === null; |
||
144 | $this->doBuild($quiet || $fromInstaller, $populate); |
||
145 | } |
||
146 | } |
||
147 | |||
148 | /** |
||
149 | * Gets the url to return to after build |
||
150 | * |
||
151 | * @return string|null |
||
152 | */ |
||
153 | protected function getReturnURL() |
||
154 | { |
||
155 | $url = $this->request->getVar('returnURL'); |
||
156 | |||
157 | // Check that this url is a site url |
||
158 | if (empty($url) || !Director::is_site_url($url)) { |
||
159 | return null; |
||
160 | } |
||
161 | |||
162 | // Convert to absolute URL |
||
163 | return Director::absoluteURL($url, true); |
||
164 | } |
||
165 | |||
166 | /** |
||
167 | * Build the default data, calling requireDefaultRecords on all |
||
168 | * DataObject classes |
||
169 | */ |
||
170 | public function buildDefaults() |
||
171 | { |
||
172 | $dataClasses = ClassInfo::subclassesFor(DataObject::class); |
||
173 | array_shift($dataClasses); |
||
174 | |||
175 | if (!Director::is_cli()) { |
||
176 | echo "<ul>"; |
||
177 | } |
||
178 | |||
179 | foreach ($dataClasses as $dataClass) { |
||
180 | singleton($dataClass)->requireDefaultRecords(); |
||
181 | if (Director::is_cli()) { |
||
182 | echo "Defaults loaded for $dataClass\n"; |
||
183 | } else { |
||
184 | echo "<li>Defaults loaded for $dataClass</li>\n"; |
||
185 | } |
||
186 | } |
||
187 | |||
188 | if (!Director::is_cli()) { |
||
189 | echo "</ul>"; |
||
190 | } |
||
191 | } |
||
192 | |||
193 | /** |
||
194 | * Returns the timestamp of the time that the database was last built |
||
195 | * |
||
196 | * @return string Returns the timestamp of the time that the database was |
||
197 | * last built |
||
198 | */ |
||
199 | public static function lastBuilt() |
||
200 | { |
||
201 | $file = TEMP_PATH |
||
202 | . DIRECTORY_SEPARATOR |
||
203 | . 'database-last-generated-' |
||
204 | . str_replace(array('\\','/',':'), '.', Director::baseFolder()); |
||
205 | |||
206 | if (file_exists($file)) { |
||
207 | return filemtime($file); |
||
208 | } |
||
209 | return null; |
||
210 | } |
||
211 | |||
212 | |||
213 | /** |
||
214 | * Updates the database schema, creating tables & fields as necessary. |
||
215 | * |
||
216 | * @param boolean $quiet Don't show messages |
||
217 | * @param boolean $populate Populate the database, as well as setting up its schema |
||
218 | * @param bool $testMode |
||
219 | */ |
||
220 | public function doBuild($quiet = false, $populate = true, $testMode = false) |
||
370 | } |
||
371 | |||
372 | /** |
||
373 | * Given a base data class, a field name and an old and new class name (value), look for obsolete ($oldClassName) |
||
374 | * values in the $dataClass's $fieldName column and replace it with $newClassName. |
||
375 | * |
||
376 | * @param string $dataClass The data class to look up |
||
377 | * @param string $fieldName The field name to look in for obsolete class names |
||
378 | * @param string $oldClassName The old class name |
||
379 | * @param string $newClassName The new class name |
||
380 | */ |
||
381 | protected function updateLegacyClassNames($dataClass, $fieldName, $oldClassName, $newClassName) |
||
382 | { |
||
383 | $schema = DataObject::getSchema(); |
||
384 | // Check first to ensure that the class has the specified field to update |
||
385 | if (!$schema->databaseField($dataClass, $fieldName, false)) { |
||
386 | return; |
||
387 | } |
||
388 | |||
389 | // Load a list of any records that have obsolete class names |
||
390 | $badRecordCount = DataObject::get($dataClass) |
||
391 | ->filter([$fieldName => $oldClassName]) |
||
392 | ->count(); |
||
393 | |||
394 | if (!$badRecordCount) { |
||
395 | return; |
||
396 | } |
||
397 | |||
398 | if (Director::is_cli()) { |
||
399 | echo " * Correcting {$badRecordCount} obsolete {$fieldName} values for {$newClassName}\n"; |
||
400 | } else { |
||
401 | echo "<li>Correcting {$badRecordCount} obsolete {$fieldName} values for {$newClassName}</li>\n"; |
||
402 | } |
||
403 | $table = $schema->tableName($dataClass); |
||
404 | |||
405 | $updateQuery = "UPDATE \"{$table}%s\" SET \"{$fieldName}\" = ? WHERE \"{$fieldName}\" = ?"; |
||
406 | $updateQueries = [sprintf($updateQuery, '')]; |
||
407 | |||
408 | // Remap versioned table class name values as well |
||
409 | /** @var Versioned|DataObject $class */ |
||
410 | $class = DataObject::singleton($dataClass); |
||
411 | if ($class->hasExtension(Versioned::class)) { |
||
412 | if ($class->hasStages()) { |
||
413 | $updateQueries[] = sprintf($updateQuery, '_Live'); |
||
414 | } |
||
415 | $updateQueries[] = sprintf($updateQuery, '_Versions'); |
||
416 | } |
||
417 | |||
418 | foreach ($updateQueries as $query) { |
||
419 | DB::prepared_query($query, [$newClassName, $oldClassName]); |
||
420 | } |
||
421 | } |
||
422 | |||
423 | /** |
||
424 | * Find all DBClassName fields on valid subclasses of DataObject that should be remapped. This includes |
||
425 | * `ClassName` fields as well as polymorphic class name fields. |
||
426 | * |
||
427 | * @return array[] |
||
428 | */ |
||
429 | protected function getClassNameRemappingFields() |
||
430 | { |
||
431 | $dataClasses = ClassInfo::getValidSubClasses(DataObject::class); |
||
432 | $schema = DataObject::getSchema(); |
||
433 | $remapping = []; |
||
434 | |||
435 | foreach ($dataClasses as $className) { |
||
436 | $fieldSpecs = $schema->fieldSpecs($className); |
||
437 | foreach ($fieldSpecs as $fieldName => $fieldSpec) { |
||
438 | if (Injector::inst()->create($fieldSpec, 'Dummy') instanceof DBClassName) { |
||
439 | $remapping[$className][] = $fieldName; |
||
440 | } |
||
441 | } |
||
442 | } |
||
443 | |||
444 | return $remapping; |
||
445 | } |
||
446 | |||
447 | /** |
||
448 | * Remove invalid records from tables - that is, records that don't have |
||
449 | * corresponding records in their parent class tables. |
||
450 | */ |
||
451 | public function cleanup() |
||
493 | } |
||
494 | } |
||
495 | } |
||
496 | } |
||
497 | } |
||
498 | } |
||
499 | } |
||
500 |