Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like AssetAdmin 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
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 AssetAdmin, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 40 | class AssetAdmin extends LeftAndMain implements PermissionProvider |
||
| 41 | { |
||
| 42 | private static $url_segment = 'assets'; |
||
| 43 | |||
| 44 | private static $url_rule = '/$Action/$ID'; |
||
| 45 | |||
| 46 | private static $menu_title = 'Files'; |
||
| 47 | |||
| 48 | private static $tree_class = 'SilverStripe\\Assets\\Folder'; |
||
| 49 | |||
| 50 | private static $url_handlers = [ |
||
| 51 | // Legacy redirect for SS3-style detail view |
||
| 52 | 'EditForm/field/File/item/$FileID/$Action' => 'legacyRedirectForEditView', |
||
| 53 | // Pass all URLs to the index, for React to unpack |
||
| 54 | 'show/$FolderID/edit/$FileID' => 'index', |
||
| 55 | // API access points with structured data |
||
| 56 | 'POST api/createFolder' => 'apiCreateFolder', |
||
| 57 | 'POST api/createFile' => 'apiCreateFile', |
||
| 58 | 'GET api/readFolder' => 'apiReadFolder', |
||
| 59 | 'PUT api/updateFolder' => 'apiUpdateFolder', |
||
| 60 | 'DELETE api/delete' => 'apiDelete', |
||
| 61 | 'GET api/search' => 'apiSearch', |
||
| 62 | ]; |
||
| 63 | |||
| 64 | /** |
||
| 65 | * Amount of results showing on a single page. |
||
| 66 | * |
||
| 67 | * @config |
||
| 68 | * @var int |
||
| 69 | */ |
||
| 70 | private static $page_length = 15; |
||
| 71 | |||
| 72 | /** |
||
| 73 | * @config |
||
| 74 | * @see Upload->allowedMaxFileSize |
||
| 75 | * @var int |
||
| 76 | */ |
||
| 77 | private static $allowed_max_file_size; |
||
| 78 | |||
| 79 | /** |
||
| 80 | * @var array |
||
| 81 | */ |
||
| 82 | private static $allowed_actions = array( |
||
| 83 | 'legacyRedirectForEditView', |
||
| 84 | 'apiCreateFolder', |
||
| 85 | 'apiCreateFile', |
||
| 86 | 'apiReadFolder', |
||
| 87 | 'apiUpdateFolder', |
||
| 88 | 'apiDelete', |
||
| 89 | 'apiSearch', |
||
| 90 | 'FileEditForm', |
||
| 91 | 'AddToCampaignForm', |
||
| 92 | ); |
||
| 93 | |||
| 94 | private static $required_permission_codes = 'CMS_ACCESS_AssetAdmin'; |
||
| 95 | |||
| 96 | /** |
||
| 97 | * Set up the controller |
||
| 98 | */ |
||
| 99 | public function init() |
||
| 100 | { |
||
| 101 | parent::init(); |
||
| 102 | |||
| 103 | Requirements::add_i18n_javascript(ASSET_ADMIN_DIR . '/client/lang', false, true); |
||
| 104 | Requirements::javascript(ASSET_ADMIN_DIR . "/client/dist/js/bundle.js"); |
||
| 105 | Requirements::css(ASSET_ADMIN_DIR . "/client/dist/styles/bundle.css"); |
||
| 106 | |||
| 107 | CMSBatchActionHandler::register( |
||
| 108 | 'delete', |
||
| 109 | 'SilverStripe\AssetAdmin\BatchAction\DeleteAssets', |
||
| 110 | 'SilverStripe\\Assets\\Folder' |
||
| 111 | ); |
||
| 112 | } |
||
| 113 | |||
| 114 | public function getClientConfig() |
||
| 115 | { |
||
| 116 | $baseLink = $this->Link(); |
||
| 117 | return array_merge( parent::getClientConfig(), [ |
||
| 118 | 'reactRouter' => true, |
||
| 119 | 'createFileEndpoint' => [ |
||
| 120 | 'url' => Controller::join_links($baseLink, 'api/createFile'), |
||
| 121 | 'method' => 'post', |
||
| 122 | 'payloadFormat' => 'urlencoded', |
||
| 123 | ], |
||
| 124 | 'createFolderEndpoint' => [ |
||
| 125 | 'url' => Controller::join_links($baseLink, 'api/createFolder'), |
||
| 126 | 'method' => 'post', |
||
| 127 | 'payloadFormat' => 'urlencoded', |
||
| 128 | ], |
||
| 129 | 'readFolderEndpoint' => [ |
||
| 130 | 'url' => Controller::join_links($baseLink, 'api/readFolder'), |
||
| 131 | 'method' => 'get', |
||
| 132 | 'responseFormat' => 'json', |
||
| 133 | ], |
||
| 134 | 'searchEndpoint' => [ |
||
| 135 | 'url' => Controller::join_links($baseLink, 'api/search'), |
||
| 136 | 'method' => 'get', |
||
| 137 | 'responseFormat' => 'json', |
||
| 138 | ], |
||
| 139 | 'updateFolderEndpoint' => [ |
||
| 140 | 'url' => Controller::join_links($baseLink, 'api/updateFolder'), |
||
| 141 | 'method' => 'put', |
||
| 142 | 'payloadFormat' => 'urlencoded', |
||
| 143 | ], |
||
| 144 | 'deleteEndpoint' => [ |
||
| 145 | 'url' => Controller::join_links($baseLink, 'api/delete'), |
||
| 146 | 'method' => 'delete', |
||
| 147 | 'payloadFormat' => 'urlencoded', |
||
| 148 | ], |
||
| 149 | 'limit' => $this->config()->page_length, |
||
| 150 | 'form' => [ |
||
| 151 | 'FileEditForm' => [ |
||
| 152 | 'schemaUrl' => $this->Link('schema/FileEditForm') |
||
| 153 | ], |
||
| 154 | 'AddToCampaignForm' => [ |
||
| 155 | 'schemaUrl' => $this->Link('schema/AddToCampaignForm') |
||
| 156 | ], |
||
| 157 | ], |
||
| 158 | ]); |
||
| 159 | } |
||
| 160 | |||
| 161 | /** |
||
| 162 | * Fetches a collection of files by ParentID. |
||
| 163 | * |
||
| 164 | * @param SS_HTTPRequest $request |
||
| 165 | * @return SS_HTTPResponse |
||
| 166 | */ |
||
| 167 | public function apiReadFolder(SS_HTTPRequest $request) |
||
| 168 | { |
||
| 169 | $params = $request->requestVars(); |
||
| 170 | $items = array(); |
||
| 171 | $parentId = null; |
||
| 172 | $folderID = null; |
||
| 173 | |||
| 174 | if (!isset($params['id']) && !strlen($params['id'])) { |
||
| 175 | $this->httpError(400); |
||
| 176 | } |
||
| 177 | |||
| 178 | $folderID = (int)$params['id']; |
||
| 179 | /** @var Folder $folder */ |
||
| 180 | $folder = $folderID ? Folder::get()->byID($folderID) : Folder::singleton(); |
||
| 181 | |||
| 182 | if (!$folder) { |
||
| 183 | $this->httpError(400); |
||
| 184 | } |
||
| 185 | |||
| 186 | // TODO Limit results to avoid running out of memory (implement client-side pagination) |
||
| 187 | $files = $this->getList()->filter('ParentID', $folderID); |
||
| 188 | |||
| 189 | if ($files) { |
||
| 190 | /** @var File $file */ |
||
| 191 | foreach ($files as $file) { |
||
| 192 | if (!$file->canView()) { |
||
| 193 | continue; |
||
| 194 | } |
||
| 195 | |||
| 196 | $items[] = $this->getObjectFromData($file); |
||
| 197 | } |
||
| 198 | } |
||
| 199 | |||
| 200 | // Build parents (for breadcrumbs) |
||
| 201 | $parents = []; |
||
| 202 | $next = $folder->Parent(); |
||
| 203 | while($next && $next->exists()) { |
||
| 204 | array_unshift($parents, [ |
||
| 205 | 'id' => $next->ID, |
||
| 206 | 'title' => $next->getTitle(), |
||
| 207 | ]); |
||
| 208 | if($next->ParentID) { |
||
| 209 | $next = $next->Parent(); |
||
| 210 | } else { |
||
| 211 | break; |
||
| 212 | } |
||
| 213 | } |
||
| 214 | |||
| 215 | // Build response |
||
| 216 | $response = new SS_HTTPResponse(); |
||
| 217 | $response->addHeader('Content-Type', 'application/json'); |
||
| 218 | $response->setBody(json_encode([ |
||
| 219 | 'files' => $items, |
||
| 220 | 'title' => $folder->getTitle(), |
||
| 221 | 'count' => count($items), |
||
| 222 | 'parents' => $parents, |
||
| 223 | 'parentID' => $folder->exists() ? $folder->ParentID : null, // grandparent |
||
| 224 | 'folderID' => $folderID, |
||
| 225 | 'canEdit' => $folder->canEdit(), |
||
| 226 | 'canDelete' => $folder->canDelete(), |
||
| 227 | ])); |
||
| 228 | |||
| 229 | return $response; |
||
| 230 | } |
||
| 231 | |||
| 232 | /** |
||
| 233 | * @param SS_HTTPRequest $request |
||
| 234 | * |
||
| 235 | * @return SS_HTTPResponse |
||
| 236 | */ |
||
| 237 | public function apiSearch(SS_HTTPRequest $request) |
||
| 254 | |||
| 255 | /** |
||
| 256 | * @param SS_HTTPRequest $request |
||
| 257 | * |
||
| 258 | * @return SS_HTTPResponse |
||
| 259 | */ |
||
| 260 | public function apiDelete(SS_HTTPRequest $request) |
||
| 261 | { |
||
| 262 | parse_str($request->getBody(), $vars); |
||
| 263 | |||
| 264 | // CSRF check |
||
| 265 | $token = SecurityToken::inst(); |
||
| 266 | View Code Duplication | if (empty($vars[$token->getName()]) || !$token->check($vars[$token->getName()])) { |
|
| 267 | return new SS_HTTPResponse(null, 400); |
||
| 268 | } |
||
| 269 | |||
| 270 | View Code Duplication | if (!isset($vars['ids']) || !$vars['ids']) { |
|
| 271 | return (new SS_HTTPResponse(json_encode(['status' => 'error']), 400)) |
||
| 272 | ->addHeader('Content-Type', 'application/json'); |
||
| 273 | } |
||
| 274 | |||
| 275 | $fileIds = $vars['ids']; |
||
| 276 | $files = $this->getList()->filter("ID", $fileIds)->toArray(); |
||
| 277 | |||
| 278 | View Code Duplication | if (!count($files)) { |
|
| 279 | return (new SS_HTTPResponse(json_encode(['status' => 'error']), 404)) |
||
| 280 | ->addHeader('Content-Type', 'application/json'); |
||
| 281 | } |
||
| 282 | |||
| 283 | if (!min(array_map(function (File $file) { |
||
| 284 | return $file->canDelete(); |
||
| 285 | }, $files))) { |
||
| 286 | return (new SS_HTTPResponse(json_encode(['status' => 'error']), 401)) |
||
| 287 | ->addHeader('Content-Type', 'application/json'); |
||
| 288 | } |
||
| 289 | |||
| 290 | /** @var File $file */ |
||
| 291 | foreach ($files as $file) { |
||
| 292 | $file->delete(); |
||
| 293 | } |
||
| 294 | |||
| 295 | return (new SS_HTTPResponse(json_encode(['status' => 'file was deleted']))) |
||
| 296 | ->addHeader('Content-Type', 'application/json'); |
||
| 297 | } |
||
| 298 | |||
| 299 | /** |
||
| 300 | * Creates a single file based on a form-urlencoded upload. |
||
| 301 | * |
||
| 302 | * @param SS_HTTPRequest $request |
||
| 303 | * @return SS_HTTPRequest|SS_HTTPResponse |
||
| 304 | */ |
||
| 305 | public function apiCreateFile(SS_HTTPRequest $request) |
||
| 306 | { |
||
| 307 | $data = $request->postVars(); |
||
| 308 | $upload = $this->getUpload(); |
||
| 309 | |||
| 310 | // CSRF check |
||
| 311 | $token = SecurityToken::inst(); |
||
| 312 | View Code Duplication | if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) { |
|
| 313 | return new SS_HTTPResponse(null, 400); |
||
| 314 | } |
||
| 315 | |||
| 316 | // check canAddChildren permissions |
||
| 317 | if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) { |
||
| 318 | $parentRecord = Folder::get()->byID($data['ParentID']); |
||
| 319 | View Code Duplication | if ($parentRecord->hasMethod('canAddChildren') && !$parentRecord->canAddChildren()) { |
|
| 320 | return (new SS_HTTPResponse(json_encode(['status' => 'error']), 403)) |
||
| 321 | ->addHeader('Content-Type', 'application/json'); |
||
| 322 | } |
||
| 323 | } else { |
||
| 324 | $parentRecord = Folder::singleton(); |
||
| 325 | } |
||
| 326 | |||
| 327 | // check create permissions |
||
| 328 | View Code Duplication | if (!$parentRecord->canCreate()) { |
|
| 329 | return (new SS_HTTPResponse(json_encode(['status' => 'error']), 403)) |
||
| 330 | ->addHeader('Content-Type', 'application/json'); |
||
| 331 | } |
||
| 332 | |||
| 333 | /** @skipUpgrade */ |
||
| 334 | $tmpFile = $request->postVar('Upload'); |
||
| 335 | if(!$upload->validate($tmpFile)) { |
||
| 336 | $result = ['error' => $upload->getErrors()]; |
||
| 337 | return (new SS_HTTPResponse(json_encode($result), 400)) |
||
| 338 | ->addHeader('Content-Type', 'application/json'); |
||
| 339 | } |
||
| 340 | |||
| 341 | // TODO Allow batch uploads |
||
| 342 | $fileClass = File::get_class_for_file_extension(File::get_file_extension($tmpFile['name'])); |
||
| 343 | $file = Injector::inst()->create($fileClass); |
||
| 344 | $uploadResult = $upload->loadIntoFile($tmpFile, $file, $parentRecord ? $parentRecord->getFilename() : '/'); |
||
| 345 | View Code Duplication | if(!$uploadResult) { |
|
| 346 | $result = ['error' => 'unknown']; |
||
| 347 | return (new SS_HTTPResponse(json_encode($result), 400)) |
||
| 348 | ->addHeader('Content-Type', 'application/json'); |
||
| 349 | } |
||
| 350 | |||
| 351 | $file->ParentID = $parentRecord->ID; |
||
| 352 | $file->write(); |
||
| 353 | |||
| 354 | $result = [$this->getObjectFromData($file)]; |
||
| 355 | |||
| 356 | return (new SS_HTTPResponse(json_encode($result))) |
||
| 357 | ->addHeader('Content-Type', 'application/json'); |
||
| 358 | } |
||
| 359 | |||
| 360 | /** |
||
| 361 | * Creates a single folder, within an optional parent folder. |
||
| 362 | * |
||
| 363 | * @param SS_HTTPRequest $request |
||
| 364 | * @return SS_HTTPRequest|SS_HTTPResponse |
||
| 365 | */ |
||
| 366 | public function apiCreateFolder(SS_HTTPRequest $request) |
||
| 367 | { |
||
| 368 | $data = $request->postVars(); |
||
| 369 | |||
| 370 | $class = 'SilverStripe\\Assets\\Folder'; |
||
| 371 | |||
| 372 | // CSRF check |
||
| 373 | $token = SecurityToken::inst(); |
||
| 374 | View Code Duplication | if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) { |
|
| 375 | return new SS_HTTPResponse(null, 400); |
||
| 376 | } |
||
| 377 | |||
| 378 | // check addchildren permissions |
||
| 379 | if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) { |
||
| 380 | $parentRecord = DataObject::get_by_id($class, $data['ParentID']); |
||
| 381 | View Code Duplication | if ($parentRecord->hasMethod('canAddChildren') && !$parentRecord->canAddChildren()) { |
|
| 382 | return (new SS_HTTPResponse(null, 403)) |
||
| 383 | ->addHeader('Content-Type', 'application/json'); |
||
| 384 | } |
||
| 385 | } else { |
||
| 386 | $parentRecord = singleton($class); |
||
| 387 | } |
||
| 388 | $data['ParentID'] = ($parentRecord->exists()) ? (int)$parentRecord->ID : 0; |
||
| 389 | |||
| 390 | // check create permissions |
||
| 391 | if (!$parentRecord->canCreate()) { |
||
| 392 | return (new SS_HTTPResponse(null, 403)) |
||
| 393 | ->addHeader('Content-Type', 'application/json'); |
||
| 394 | } |
||
| 395 | |||
| 396 | // Build filename |
||
| 397 | $baseFilename = isset($data['Name']) |
||
| 398 | ? basename($data['Name']) |
||
| 399 | : _t('AssetAdmin.NEWFOLDER', "NewFolder"); |
||
| 400 | |||
| 401 | if ($parentRecord && $parentRecord->ID) { |
||
| 402 | $baseFilename = $parentRecord->getFilename() . '/' . $baseFilename; |
||
| 403 | } |
||
| 404 | |||
| 405 | // Ensure name is unique |
||
| 406 | $nameGenerator = $this->getNameGenerator($baseFilename); |
||
| 407 | $filename = null; |
||
| 408 | foreach ($nameGenerator as $filename) { |
||
| 409 | if (! File::find($filename)) { |
||
| 410 | break; |
||
| 411 | } |
||
| 412 | } |
||
| 413 | $data['Name'] = basename($filename); |
||
| 414 | |||
| 415 | // Create record |
||
| 416 | /** @var Folder $record */ |
||
| 417 | $record = Injector::inst()->create($class); |
||
| 418 | $record->ParentID = $data['ParentID']; |
||
| 419 | $record->Name = $record->Title = basename($data['Name']); |
||
| 420 | $record->write(); |
||
| 421 | |||
| 422 | $result = $this->getObjectFromData($record); |
||
| 423 | |||
| 424 | return (new SS_HTTPResponse(json_encode($result)))->addHeader('Content-Type', 'application/json'); |
||
| 425 | } |
||
| 426 | |||
| 427 | /** |
||
| 428 | * Redirects 3.x style detail links to new 4.x style routing. |
||
| 429 | * |
||
| 430 | * @param SS_HTTPRequest $request |
||
| 431 | */ |
||
| 432 | public function legacyRedirectForEditView($request) |
||
| 433 | { |
||
| 434 | $fileID = $request->param('FileID'); |
||
| 435 | /** @var File $file */ |
||
| 436 | $file = File::get()->byID($fileID); |
||
| 437 | $link = $this->getFileEditLink($file) ?: $this->Link(); |
||
| 438 | $this->redirect($link); |
||
| 439 | } |
||
| 440 | |||
| 441 | /** |
||
| 442 | * Given a file return the CMS link to edit it |
||
| 443 | * |
||
| 444 | * @param File $file |
||
| 445 | * @return string |
||
| 446 | */ |
||
| 447 | public function getFileEditLink($file) { |
||
| 459 | |||
| 460 | /** |
||
| 461 | * Get the search context from {@link File}, used to create the search form |
||
| 462 | * as well as power the /search API endpoint. |
||
| 463 | * |
||
| 464 | * @return SearchContext |
||
| 465 | */ |
||
| 466 | public function getSearchContext() |
||
| 508 | |||
| 509 | /** |
||
| 510 | * Get an asset renamer for the given filename. |
||
| 511 | * |
||
| 512 | * @param string $filename Path name |
||
| 513 | * @return AssetNameGenerator |
||
| 514 | */ |
||
| 515 | protected function getNameGenerator($filename) |
||
| 520 | |||
| 521 | /** |
||
| 522 | * @todo Implement on client |
||
| 523 | * |
||
| 524 | * @param bool $unlinked |
||
| 525 | * @return ArrayList |
||
| 526 | */ |
||
| 527 | public function breadcrumbs($unlinked = false) |
||
| 531 | |||
| 532 | |||
| 533 | /** |
||
| 534 | * Don't include class namespace in auto-generated CSS class |
||
| 535 | */ |
||
| 536 | public function baseCSSClasses() |
||
| 540 | |||
| 541 | public function providePermissions() |
||
| 552 | |||
| 553 | /** |
||
| 554 | * The form is used to generate a form schema, |
||
| 555 | * as well as an intermediary object to process data through API endpoints. |
||
| 556 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
| 557 | * It handles both {@link File} and {@link Folder} records. |
||
| 558 | * |
||
| 559 | * @param int $id |
||
| 560 | * @return Form |
||
| 561 | */ |
||
| 562 | public function getFileEditForm($id) |
||
| 615 | |||
| 616 | /** |
||
| 617 | * Get file edit form |
||
| 618 | * |
||
| 619 | * @return Form |
||
| 620 | */ |
||
| 621 | public function FileEditForm() |
||
| 628 | |||
| 629 | /** |
||
| 630 | * @param array $data |
||
| 631 | * @param Form $form |
||
| 632 | * @return SS_HTTPResponse |
||
| 633 | */ |
||
| 634 | public function save($data, $form) |
||
| 664 | |||
| 665 | /** |
||
| 666 | * @param File $file |
||
| 667 | * |
||
| 668 | * @return array |
||
| 669 | */ |
||
| 670 | protected function getObjectFromData(File $file) |
||
| 720 | |||
| 721 | |||
| 722 | /** |
||
| 723 | * Returns the files and subfolders contained in the currently selected folder, |
||
| 724 | * defaulting to the root node. Doubles as search results, if any search parameters |
||
| 725 | * are set through {@link SearchForm()}. |
||
| 726 | * |
||
| 727 | * @param array $params Unsanitised request parameters |
||
| 728 | * @return DataList |
||
| 729 | */ |
||
| 730 | protected function getList($params = array()) |
||
| 790 | |||
| 791 | /** |
||
| 792 | * Action handler for adding pages to a campaign |
||
| 793 | * |
||
| 794 | * @param array $data |
||
| 795 | * @param Form $form |
||
| 796 | * @return DBHTMLText|SS_HTTPResponse |
||
| 797 | */ |
||
| 798 | public function addtocampaign($data, $form) |
||
| 818 | |||
| 819 | /** |
||
| 820 | * Url handler for add to campaign form |
||
| 821 | * |
||
| 822 | * @param SS_HTTPRequest $request |
||
| 823 | * @return Form |
||
| 824 | */ |
||
| 825 | public function AddToCampaignForm($request) |
||
| 831 | |||
| 832 | /** |
||
| 833 | * @param int $id |
||
| 834 | * @return Form |
||
| 835 | */ |
||
| 836 | public function getAddToCampaignForm($id) |
||
| 863 | |||
| 864 | /** |
||
| 865 | * @return Upload |
||
| 866 | */ |
||
| 867 | protected function getUpload() |
||
| 877 | } |
||
| 878 |
This check marks private properties in classes that are never used. Those properties can be removed.