| Total Complexity | 95 |
| Total Lines | 502 |
| 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 |
||
| 26 | class DatabaseAdmin extends Controller |
||
| 27 | { |
||
| 28 | |||
| 29 | /// SECURITY /// |
||
| 30 | private static $allowed_actions = array( |
||
|
|
|||
| 31 | 'index', |
||
| 32 | 'build', |
||
| 33 | 'cleanup', |
||
| 34 | 'import' |
||
| 35 | ); |
||
| 36 | |||
| 37 | /** |
||
| 38 | * Obsolete classname values that should be remapped in dev/build |
||
| 39 | */ |
||
| 40 | private static $classname_value_remapping = [ |
||
| 41 | 'File' => 'SilverStripe\\Assets\\File', |
||
| 42 | 'Image' => 'SilverStripe\\Assets\\Image', |
||
| 43 | 'Folder' => 'SilverStripe\\Assets\\Folder', |
||
| 44 | 'Group' => 'SilverStripe\\Security\\Group', |
||
| 45 | 'LoginAttempt' => 'SilverStripe\\Security\\LoginAttempt', |
||
| 46 | 'Member' => 'SilverStripe\\Security\\Member', |
||
| 47 | 'MemberPassword' => 'SilverStripe\\Security\\MemberPassword', |
||
| 48 | 'Permission' => 'SilverStripe\\Security\\Permission', |
||
| 49 | 'PermissionRole' => 'SilverStripe\\Security\\PermissionRole', |
||
| 50 | 'PermissionRoleCode' => 'SilverStripe\\Security\\PermissionRoleCode', |
||
| 51 | 'RememberLoginHash' => 'SilverStripe\\Security\\RememberLoginHash', |
||
| 52 | ]; |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Config setting to enabled/disable the display of record counts on the dev/build output |
||
| 56 | */ |
||
| 57 | private static $show_record_counts = true; |
||
| 58 | |||
| 59 | protected function init() |
||
| 60 | { |
||
| 61 | parent::init(); |
||
| 62 | |||
| 63 | // We allow access to this controller regardless of live-status or ADMIN permission only |
||
| 64 | // if on CLI or with the database not ready. The latter makes it less errorprone to do an |
||
| 65 | // initial schema build without requiring a default-admin login. |
||
| 66 | // Access to this controller is always allowed in "dev-mode", or of the user is ADMIN. |
||
| 67 | $allowAllCLI = DevelopmentAdmin::config()->get('allow_all_cli'); |
||
| 68 | $canAccess = ( |
||
| 69 | Director::isDev() |
||
| 70 | || !Security::database_is_ready() |
||
| 71 | // We need to ensure that DevelopmentAdminTest can simulate permission failures when running |
||
| 72 | // "dev/tests" from CLI. |
||
| 73 | || (Director::is_cli() && $allowAllCLI) |
||
| 74 | || Permission::check("ADMIN") |
||
| 75 | ); |
||
| 76 | if (!$canAccess) { |
||
| 77 | Security::permissionFailure( |
||
| 78 | $this, |
||
| 79 | "This page is secured and you need administrator rights to access it. " . |
||
| 80 | "Enter your credentials below and we will send you right along." |
||
| 81 | ); |
||
| 82 | } |
||
| 83 | } |
||
| 84 | |||
| 85 | /** |
||
| 86 | * Get the data classes, grouped by their root class |
||
| 87 | * |
||
| 88 | * @return array Array of data classes, grouped by their root class |
||
| 89 | */ |
||
| 90 | public function groupedDataClasses() |
||
| 91 | { |
||
| 92 | // Get all root data objects |
||
| 93 | $allClasses = get_declared_classes(); |
||
| 94 | $rootClasses = []; |
||
| 95 | foreach ($allClasses as $class) { |
||
| 96 | if (get_parent_class($class) == DataObject::class) { |
||
| 97 | $rootClasses[$class] = array(); |
||
| 98 | } |
||
| 99 | } |
||
| 100 | |||
| 101 | // Assign every other data object one of those |
||
| 102 | foreach ($allClasses as $class) { |
||
| 103 | if (!isset($rootClasses[$class]) && is_subclass_of($class, DataObject::class)) { |
||
| 104 | foreach ($rootClasses as $rootClass => $dummy) { |
||
| 105 | if (is_subclass_of($class, $rootClass)) { |
||
| 106 | $rootClasses[$rootClass][] = $class; |
||
| 107 | break; |
||
| 108 | } |
||
| 109 | } |
||
| 110 | } |
||
| 111 | } |
||
| 112 | return $rootClasses; |
||
| 113 | } |
||
| 114 | |||
| 115 | |||
| 116 | /** |
||
| 117 | * When we're called as /dev/build, that's actually the index. Do the same |
||
| 118 | * as /dev/build/build. |
||
| 119 | */ |
||
| 120 | public function index() |
||
| 121 | { |
||
| 122 | return $this->build(); |
||
| 123 | } |
||
| 124 | |||
| 125 | /** |
||
| 126 | * Updates the database schema, creating tables & fields as necessary. |
||
| 127 | */ |
||
| 128 | public function build() |
||
| 129 | { |
||
| 130 | // The default time limit of 30 seconds is normally not enough |
||
| 131 | Environment::increaseTimeLimitTo(600); |
||
| 132 | |||
| 133 | // If this code is being run outside of a dev/build or without a ?flush query string param, |
||
| 134 | // the class manifest hasn't been flushed, so do it here |
||
| 135 | $request = $this->getRequest(); |
||
| 136 | if (!array_key_exists('flush', $request->getVars()) && strpos($request->getURL(), 'dev/build') !== 0) { |
||
| 137 | ClassLoader::inst()->getManifest()->regenerate(false); |
||
| 138 | } |
||
| 139 | |||
| 140 | $url = $this->getReturnURL(); |
||
| 141 | if ($url) { |
||
| 142 | echo "<p>Setting up the database; you will be returned to your site shortly....</p>"; |
||
| 143 | $this->doBuild(true); |
||
| 144 | echo "<p>Done!</p>"; |
||
| 145 | $this->redirect($url); |
||
| 146 | } else { |
||
| 147 | $quiet = $this->request->requestVar('quiet') !== null; |
||
| 148 | $fromInstaller = $this->request->requestVar('from_installer') !== null; |
||
| 149 | $populate = $this->request->requestVar('dont_populate') === null; |
||
| 150 | $this->doBuild($quiet || $fromInstaller, $populate); |
||
| 151 | } |
||
| 152 | } |
||
| 153 | |||
| 154 | /** |
||
| 155 | * Gets the url to return to after build |
||
| 156 | * |
||
| 157 | * @return string|null |
||
| 158 | */ |
||
| 159 | protected function getReturnURL() |
||
| 160 | { |
||
| 161 | $url = $this->request->getVar('returnURL'); |
||
| 162 | |||
| 163 | // Check that this url is a site url |
||
| 164 | if (empty($url) || !Director::is_site_url($url)) { |
||
| 165 | return null; |
||
| 166 | } |
||
| 167 | |||
| 168 | // Convert to absolute URL |
||
| 169 | return Director::absoluteURL($url, true); |
||
| 170 | } |
||
| 171 | |||
| 172 | /** |
||
| 173 | * Build the default data, calling requireDefaultRecords on all |
||
| 174 | * DataObject classes |
||
| 175 | */ |
||
| 176 | public function buildDefaults() |
||
| 177 | { |
||
| 178 | $dataClasses = ClassInfo::subclassesFor(DataObject::class); |
||
| 179 | array_shift($dataClasses); |
||
| 180 | |||
| 181 | if (!Director::is_cli()) { |
||
| 182 | echo "<ul>"; |
||
| 183 | } |
||
| 184 | |||
| 185 | foreach ($dataClasses as $dataClass) { |
||
| 186 | singleton($dataClass)->requireDefaultRecords(); |
||
| 187 | if (Director::is_cli()) { |
||
| 188 | echo "Defaults loaded for $dataClass\n"; |
||
| 189 | } else { |
||
| 190 | echo "<li>Defaults loaded for $dataClass</li>\n"; |
||
| 191 | } |
||
| 192 | } |
||
| 193 | |||
| 194 | if (!Director::is_cli()) { |
||
| 195 | echo "</ul>"; |
||
| 196 | } |
||
| 197 | } |
||
| 198 | |||
| 199 | /** |
||
| 200 | * Returns the timestamp of the time that the database was last built |
||
| 201 | * |
||
| 202 | * @return string Returns the timestamp of the time that the database was |
||
| 203 | * last built |
||
| 204 | */ |
||
| 205 | public static function lastBuilt() |
||
| 206 | { |
||
| 207 | $file = TEMP_PATH |
||
| 208 | . DIRECTORY_SEPARATOR |
||
| 209 | . 'database-last-generated-' |
||
| 210 | . str_replace(array('\\','/',':'), '.', Director::baseFolder()); |
||
| 211 | |||
| 212 | if (file_exists($file)) { |
||
| 213 | return filemtime($file); |
||
| 214 | } |
||
| 215 | return null; |
||
| 216 | } |
||
| 217 | |||
| 218 | |||
| 219 | /** |
||
| 220 | * Updates the database schema, creating tables & fields as necessary. |
||
| 221 | * |
||
| 222 | * @param boolean $quiet Don't show messages |
||
| 223 | * @param boolean $populate Populate the database, as well as setting up its schema |
||
| 224 | * @param bool $testMode |
||
| 225 | */ |
||
| 226 | public function doBuild($quiet = false, $populate = true, $testMode = false) |
||
| 405 | } |
||
| 406 | |||
| 407 | /** |
||
| 408 | * Given a base data class, a field name and an old and new class name (value), look for obsolete ($oldClassName) |
||
| 409 | * values in the $dataClass's $fieldName column and replace it with $newClassName. |
||
| 410 | * |
||
| 411 | * @param string $dataClass The data class to look up |
||
| 412 | * @param string $fieldName The field name to look in for obsolete class names |
||
| 413 | * @param string $oldClassName The old class name |
||
| 414 | * @param string $newClassName The new class name |
||
| 415 | */ |
||
| 416 | protected function updateLegacyClassNames($dataClass, $fieldName, $oldClassName, $newClassName) |
||
| 417 | { |
||
| 418 | $schema = DataObject::getSchema(); |
||
| 419 | // Check first to ensure that the class has the specified field to update |
||
| 420 | if (!$schema->databaseField($dataClass, $fieldName, false)) { |
||
| 421 | return; |
||
| 422 | } |
||
| 423 | |||
| 424 | // Load a list of any records that have obsolete class names |
||
| 425 | $badRecordCount = DataObject::get($dataClass) |
||
| 426 | ->filter([$fieldName => $oldClassName]) |
||
| 427 | ->count(); |
||
| 428 | |||
| 429 | if (!$badRecordCount) { |
||
| 430 | return; |
||
| 431 | } |
||
| 432 | |||
| 433 | if (Director::is_cli()) { |
||
| 434 | echo " * Correcting {$badRecordCount} obsolete {$fieldName} values for {$newClassName}\n"; |
||
| 435 | } else { |
||
| 436 | echo "<li>Correcting {$badRecordCount} obsolete {$fieldName} values for {$newClassName}</li>\n"; |
||
| 437 | } |
||
| 438 | $table = $schema->tableName($dataClass); |
||
| 439 | |||
| 440 | $updateQuery = "UPDATE \"{$table}%s\" SET \"{$fieldName}\" = ? WHERE \"{$fieldName}\" = ?"; |
||
| 441 | $updateQueries = [sprintf($updateQuery, '')]; |
||
| 442 | |||
| 443 | // Remap versioned table class name values as well |
||
| 444 | /** @var Versioned|DataObject $class */ |
||
| 445 | $class = DataObject::singleton($dataClass); |
||
| 446 | if ($class->hasExtension(Versioned::class)) { |
||
| 447 | if ($class->hasStages()) { |
||
| 448 | $updateQueries[] = sprintf($updateQuery, '_Live'); |
||
| 449 | } |
||
| 450 | $updateQueries[] = sprintf($updateQuery, '_Versions'); |
||
| 451 | } |
||
| 452 | |||
| 453 | foreach ($updateQueries as $query) { |
||
| 454 | DB::prepared_query($query, [$newClassName, $oldClassName]); |
||
| 455 | } |
||
| 456 | } |
||
| 457 | |||
| 458 | /** |
||
| 459 | * Find all DBClassName fields on valid subclasses of DataObject that should be remapped. This includes |
||
| 460 | * `ClassName` fields as well as polymorphic class name fields. |
||
| 461 | * |
||
| 462 | * @return array[] |
||
| 463 | */ |
||
| 464 | protected function getClassNameRemappingFields() |
||
| 465 | { |
||
| 466 | $dataClasses = ClassInfo::getValidSubClasses(DataObject::class); |
||
| 467 | $schema = DataObject::getSchema(); |
||
| 468 | $remapping = []; |
||
| 469 | |||
| 470 | foreach ($dataClasses as $className) { |
||
| 471 | $fieldSpecs = $schema->fieldSpecs($className); |
||
| 472 | foreach ($fieldSpecs as $fieldName => $fieldSpec) { |
||
| 473 | if (Injector::inst()->create($fieldSpec, 'Dummy') instanceof DBClassName) { |
||
| 474 | $remapping[$className][] = $fieldName; |
||
| 475 | } |
||
| 476 | } |
||
| 477 | } |
||
| 478 | |||
| 479 | return $remapping; |
||
| 480 | } |
||
| 481 | |||
| 482 | /** |
||
| 483 | * Remove invalid records from tables - that is, records that don't have |
||
| 484 | * corresponding records in their parent class tables. |
||
| 485 | */ |
||
| 486 | public function cleanup() |
||
| 528 | } |
||
| 529 | } |
||
| 530 | } |
||
| 531 | } |
||
| 532 | } |
||
| 533 | } |
||
| 534 | } |
||
| 535 |