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 |
||
| 41 | class AssetAdmin extends LeftAndMain implements PermissionProvider |
||
| 42 | { |
||
| 43 | private static $url_segment = 'assets'; |
||
| 44 | |||
| 45 | private static $url_rule = '/$Action/$ID'; |
||
| 46 | |||
| 47 | private static $menu_title = 'Files'; |
||
| 48 | |||
| 49 | private static $tree_class = 'SilverStripe\\Assets\\Folder'; |
||
| 50 | |||
| 51 | private static $url_handlers = [ |
||
| 52 | // Legacy redirect for SS3-style detail view |
||
| 53 | 'EditForm/field/File/item/$FileID/$Action' => 'legacyRedirectForEditView', |
||
| 54 | // Pass all URLs to the index, for React to unpack |
||
| 55 | 'show/$FolderID/edit/$FileID' => 'index', |
||
| 56 | // API access points with structured data |
||
| 57 | 'POST api/createFolder' => 'apiCreateFolder', |
||
| 58 | 'POST api/createFile' => 'apiCreateFile', |
||
| 59 | 'GET api/readFolder' => 'apiReadFolder', |
||
| 60 | 'PUT api/updateFolder' => 'apiUpdateFolder', |
||
| 61 | 'DELETE api/delete' => 'apiDelete', |
||
| 62 | 'GET api/search' => 'apiSearch', |
||
| 63 | ]; |
||
| 64 | |||
| 65 | /** |
||
| 66 | * Amount of results showing on a single page. |
||
| 67 | * |
||
| 68 | * @config |
||
| 69 | * @var int |
||
| 70 | */ |
||
| 71 | private static $page_length = 15; |
||
| 72 | |||
| 73 | /** |
||
| 74 | * @config |
||
| 75 | * @see Upload->allowedMaxFileSize |
||
| 76 | * @var int |
||
| 77 | */ |
||
| 78 | private static $allowed_max_file_size; |
||
| 79 | |||
| 80 | /** |
||
| 81 | * @var array |
||
| 82 | */ |
||
| 83 | private static $allowed_actions = array( |
||
| 84 | 'legacyRedirectForEditView', |
||
| 85 | 'apiCreateFolder', |
||
| 86 | 'apiCreateFile', |
||
| 87 | 'apiReadFolder', |
||
| 88 | 'apiUpdateFolder', |
||
| 89 | 'apiDelete', |
||
| 90 | 'apiSearch', |
||
| 91 | 'fileEditForm', |
||
| 92 | 'addToCampaignForm', |
||
| 93 | ); |
||
| 94 | |||
| 95 | private static $required_permission_codes = 'CMS_ACCESS_AssetAdmin'; |
||
| 96 | |||
| 97 | private static $thumbnail_width = 400; |
||
| 98 | |||
| 99 | private static $thumbnail_height = 300; |
||
| 100 | |||
| 101 | /** |
||
| 102 | * Set up the controller |
||
| 103 | */ |
||
| 104 | public function init() |
||
| 105 | { |
||
| 106 | parent::init(); |
||
| 107 | |||
| 108 | Requirements::add_i18n_javascript(ASSET_ADMIN_DIR . '/client/lang', false, true); |
||
| 109 | Requirements::javascript(ASSET_ADMIN_DIR . "/client/dist/js/bundle.js"); |
||
| 110 | Requirements::css(ASSET_ADMIN_DIR . "/client/dist/styles/bundle.css"); |
||
| 111 | |||
| 112 | CMSBatchActionHandler::register( |
||
| 113 | 'delete', |
||
| 114 | 'SilverStripe\AssetAdmin\BatchAction\DeleteAssets', |
||
| 115 | 'SilverStripe\\Assets\\Folder' |
||
| 116 | ); |
||
| 117 | } |
||
| 118 | |||
| 119 | public function getClientConfig() |
||
| 120 | { |
||
| 121 | $baseLink = $this->Link(); |
||
| 122 | return array_merge(parent::getClientConfig(), [ |
||
| 123 | 'reactRouter' => true, |
||
| 124 | 'createFileEndpoint' => [ |
||
| 125 | 'url' => Controller::join_links($baseLink, 'api/createFile'), |
||
| 126 | 'method' => 'post', |
||
| 127 | 'payloadFormat' => 'urlencoded', |
||
| 128 | ], |
||
| 129 | 'createFolderEndpoint' => [ |
||
| 130 | 'url' => Controller::join_links($baseLink, 'api/createFolder'), |
||
| 131 | 'method' => 'post', |
||
| 132 | 'payloadFormat' => 'urlencoded', |
||
| 133 | ], |
||
| 134 | 'readFolderEndpoint' => [ |
||
| 135 | 'url' => Controller::join_links($baseLink, 'api/readFolder'), |
||
| 136 | 'method' => 'get', |
||
| 137 | 'responseFormat' => 'json', |
||
| 138 | ], |
||
| 139 | 'searchEndpoint' => [ |
||
| 140 | 'url' => Controller::join_links($baseLink, 'api/search'), |
||
| 141 | 'method' => 'get', |
||
| 142 | 'responseFormat' => 'json', |
||
| 143 | ], |
||
| 144 | 'updateFolderEndpoint' => [ |
||
| 145 | 'url' => Controller::join_links($baseLink, 'api/updateFolder'), |
||
| 146 | 'method' => 'put', |
||
| 147 | 'payloadFormat' => 'urlencoded', |
||
| 148 | ], |
||
| 149 | 'deleteEndpoint' => [ |
||
| 150 | 'url' => Controller::join_links($baseLink, 'api/delete'), |
||
| 151 | 'method' => 'delete', |
||
| 152 | 'payloadFormat' => 'urlencoded', |
||
| 153 | ], |
||
| 154 | 'limit' => $this->config()->page_length, |
||
| 155 | 'form' => [ |
||
| 156 | 'fileEditForm' => [ |
||
| 157 | 'schemaUrl' => $this->Link('schema/fileEditForm') |
||
| 158 | ], |
||
| 159 | 'addToCampaignForm' => [ |
||
| 160 | 'schemaUrl' => $this->Link('schema/addToCampaignForm') |
||
| 161 | ], |
||
| 162 | ], |
||
| 163 | ]); |
||
| 164 | } |
||
| 165 | |||
| 166 | /** |
||
| 167 | * Fetches a collection of files by ParentID. |
||
| 168 | * |
||
| 169 | * @param HTTPRequest $request |
||
| 170 | * @return HTTPResponse |
||
| 171 | */ |
||
| 172 | public function apiReadFolder(HTTPRequest $request) |
||
| 173 | { |
||
| 174 | $params = $request->requestVars(); |
||
| 175 | $items = array(); |
||
| 176 | $parentId = null; |
||
| 177 | $folderID = null; |
||
| 178 | |||
| 179 | if (!isset($params['id']) && !strlen($params['id'])) { |
||
| 180 | $this->httpError(400); |
||
| 181 | } |
||
| 182 | |||
| 183 | $folderID = (int)$params['id']; |
||
| 184 | /** @var Folder $folder */ |
||
| 185 | $folder = $folderID ? Folder::get()->byID($folderID) : Folder::singleton(); |
||
| 186 | |||
| 187 | if (!$folder) { |
||
| 188 | $this->httpError(400); |
||
| 189 | } |
||
| 190 | |||
| 191 | // TODO Limit results to avoid running out of memory (implement client-side pagination) |
||
| 192 | $files = $this->getList()->filter('ParentID', $folderID); |
||
| 193 | |||
| 194 | if ($files) { |
||
| 195 | /** @var File $file */ |
||
| 196 | foreach ($files as $file) { |
||
| 197 | if (!$file->canView()) { |
||
| 198 | continue; |
||
| 199 | } |
||
| 200 | |||
| 201 | $items[] = $this->getObjectFromData($file); |
||
| 202 | } |
||
| 203 | } |
||
| 204 | |||
| 205 | // Build parents (for breadcrumbs) |
||
| 206 | $parents = []; |
||
| 207 | $next = $folder->Parent(); |
||
| 208 | while ($next && $next->exists()) { |
||
| 209 | array_unshift($parents, [ |
||
| 210 | 'id' => $next->ID, |
||
| 211 | 'title' => $next->getTitle(), |
||
| 212 | 'filename' => $next->getFilename(), |
||
| 213 | ]); |
||
| 214 | if ($next->ParentID) { |
||
| 215 | $next = $next->Parent(); |
||
| 216 | } else { |
||
| 217 | break; |
||
| 218 | } |
||
| 219 | } |
||
| 220 | |||
| 221 | // Build response |
||
| 222 | $response = new HTTPResponse(); |
||
| 223 | $response->addHeader('Content-Type', 'application/json'); |
||
| 224 | $response->setBody(json_encode([ |
||
| 225 | 'files' => $items, |
||
| 226 | 'title' => $folder->getTitle(), |
||
| 227 | 'count' => count($items), |
||
| 228 | 'parents' => $parents, |
||
| 229 | 'parent' => $parents ? $parents[count($parents) - 1] : null, |
||
| 230 | 'parentID' => $folder->exists() ? $folder->ParentID : null, // grandparent |
||
| 231 | 'folderID' => $folderID, |
||
| 232 | 'canEdit' => $folder->canEdit(), |
||
| 233 | 'canDelete' => $folder->canDelete(), |
||
| 234 | ])); |
||
| 235 | |||
| 236 | return $response; |
||
| 237 | } |
||
| 238 | |||
| 239 | /** |
||
| 240 | * @param HTTPRequest $request |
||
| 241 | * |
||
| 242 | * @return HTTPResponse |
||
| 243 | */ |
||
| 244 | public function apiSearch(HTTPRequest $request) |
||
| 261 | |||
| 262 | /** |
||
| 263 | * @param HTTPRequest $request |
||
| 264 | * |
||
| 265 | * @return HTTPResponse |
||
| 266 | */ |
||
| 267 | public function apiDelete(HTTPRequest $request) |
||
| 305 | |||
| 306 | /** |
||
| 307 | * Creates a single file based on a form-urlencoded upload. |
||
| 308 | * |
||
| 309 | * @param HTTPRequest $request |
||
| 310 | * @return HTTPRequest|HTTPResponse |
||
| 311 | */ |
||
| 312 | public function apiCreateFile(HTTPRequest $request) |
||
| 313 | { |
||
| 314 | $data = $request->postVars(); |
||
| 315 | $upload = $this->getUpload(); |
||
| 316 | |||
| 317 | // CSRF check |
||
| 318 | $token = SecurityToken::inst(); |
||
| 319 | View Code Duplication | if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) { |
|
| 320 | return new HTTPResponse(null, 400); |
||
| 321 | } |
||
| 322 | |||
| 323 | // Check parent record |
||
| 324 | /** @var Folder $parentRecord */ |
||
| 325 | $parentRecord = null; |
||
| 326 | if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) { |
||
| 327 | $parentRecord = Folder::get()->byID($data['ParentID']); |
||
| 328 | } |
||
| 329 | $data['Parent'] = $parentRecord; |
||
| 330 | |||
| 331 | $tmpFile = $request->postVar('Upload'); |
||
| 332 | View Code Duplication | if (!$upload->validate($tmpFile)) { |
|
| 333 | $result = ['error' => $upload->getErrors()]; |
||
| 334 | return (new HTTPResponse(json_encode($result), 400)) |
||
| 335 | ->addHeader('Content-Type', 'application/json'); |
||
| 336 | } |
||
| 337 | |||
| 338 | // TODO Allow batch uploads |
||
| 339 | $fileClass = File::get_class_for_file_extension(File::get_file_extension($tmpFile['name'])); |
||
| 340 | /** @var File $file */ |
||
| 341 | $file = Injector::inst()->create($fileClass); |
||
| 342 | |||
| 343 | // check canCreate permissions |
||
| 344 | View Code Duplication | if (!$file->canCreate(null, $data)) { |
|
| 345 | return (new HTTPResponse(json_encode(['status' => 'error']), 403)) |
||
| 346 | ->addHeader('Content-Type', 'application/json'); |
||
| 347 | } |
||
| 348 | |||
| 349 | $uploadResult = $upload->loadIntoFile($tmpFile, $file, $parentRecord ? $parentRecord->getFilename() : '/'); |
||
| 350 | View Code Duplication | if (!$uploadResult) { |
|
| 351 | $result = ['error' => 'unknown']; |
||
| 352 | return (new HTTPResponse(json_encode($result), 400)) |
||
| 353 | ->addHeader('Content-Type', 'application/json'); |
||
| 354 | } |
||
| 355 | |||
| 356 | $file->ParentID = $parentRecord ? $parentRecord->ID : 0; |
||
| 357 | $file->write(); |
||
| 358 | |||
| 359 | $result = [$this->getObjectFromData($file)]; |
||
| 360 | |||
| 361 | return (new HTTPResponse(json_encode($result))) |
||
| 362 | ->addHeader('Content-Type', 'application/json'); |
||
| 363 | } |
||
| 364 | |||
| 365 | /** |
||
| 366 | * Creates a single folder, within an optional parent folder. |
||
| 367 | * |
||
| 368 | * @param HTTPRequest $request |
||
| 369 | * @return HTTPRequest|HTTPResponse |
||
| 370 | */ |
||
| 371 | public function apiCreateFolder(HTTPRequest $request) |
||
| 429 | |||
| 430 | /** |
||
| 431 | * Redirects 3.x style detail links to new 4.x style routing. |
||
| 432 | * |
||
| 433 | * @param HTTPRequest $request |
||
| 434 | */ |
||
| 435 | public function legacyRedirectForEditView($request) |
||
| 443 | |||
| 444 | /** |
||
| 445 | * Given a file return the CMS link to edit it |
||
| 446 | * |
||
| 447 | * @param File $file |
||
| 448 | * @return string |
||
| 449 | */ |
||
| 450 | public function getFileEditLink($file) |
||
| 463 | |||
| 464 | /** |
||
| 465 | * Get the search context from {@link File}, used to create the search form |
||
| 466 | * as well as power the /search API endpoint. |
||
| 467 | * |
||
| 468 | * @return SearchContext |
||
| 469 | */ |
||
| 470 | public function getSearchContext() |
||
| 523 | |||
| 524 | /** |
||
| 525 | * Get an asset renamer for the given filename. |
||
| 526 | * |
||
| 527 | * @param string $filename Path name |
||
| 528 | * @return AssetNameGenerator |
||
| 529 | */ |
||
| 530 | protected function getNameGenerator($filename) |
||
| 535 | |||
| 536 | /** |
||
| 537 | * @todo Implement on client |
||
| 538 | * |
||
| 539 | * @param bool $unlinked |
||
| 540 | * @return ArrayList |
||
| 541 | */ |
||
| 542 | public function breadcrumbs($unlinked = false) |
||
| 546 | |||
| 547 | |||
| 548 | /** |
||
| 549 | * Don't include class namespace in auto-generated CSS class |
||
| 550 | */ |
||
| 551 | public function baseCSSClasses() |
||
| 555 | |||
| 556 | public function providePermissions() |
||
| 567 | |||
| 568 | /** |
||
| 569 | * The form is used to generate a form schema, |
||
| 570 | * as well as an intermediary object to process data through API endpoints. |
||
| 571 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
| 572 | * It handles both {@link File} and {@link Folder} records. |
||
| 573 | * |
||
| 574 | * @param int $id |
||
| 575 | * @return Form |
||
| 576 | */ |
||
| 577 | public function getFileEditForm($id) |
||
| 616 | |||
| 617 | /** |
||
| 618 | * Get file edit form |
||
| 619 | * |
||
| 620 | * @return Form |
||
| 621 | */ |
||
| 622 | public function fileEditForm() |
||
| 629 | |||
| 630 | /** |
||
| 631 | * @param array $data |
||
| 632 | * @param Form $form |
||
| 633 | * @return HTTPResponse |
||
| 634 | */ |
||
| 635 | public function save($data, $form) |
||
| 639 | |||
| 640 | |||
| 641 | /** |
||
| 642 | * @param array $data |
||
| 643 | * @param Form $form |
||
| 644 | * @return HTTPResponse |
||
| 645 | */ |
||
| 646 | public function publish($data, $form) |
||
| 650 | |||
| 651 | /** |
||
| 652 | * Update thisrecord |
||
| 653 | * |
||
| 654 | * @param array $data |
||
| 655 | * @param Form $form |
||
| 656 | * @param bool $doPublish |
||
| 657 | * @return HTTPResponse |
||
| 658 | */ |
||
| 659 | protected function saveOrPublish($data, $form, $doPublish = false) |
||
| 695 | |||
| 696 | public function unpublish($data, $form) |
||
| 726 | |||
| 727 | /** |
||
| 728 | * @param File $file |
||
| 729 | * |
||
| 730 | * @return array |
||
| 731 | */ |
||
| 732 | protected function getObjectFromData(File $file) |
||
| 792 | |||
| 793 | |||
| 794 | /** |
||
| 795 | * Returns the files and subfolders contained in the currently selected folder, |
||
| 796 | * defaulting to the root node. Doubles as search results, if any search parameters |
||
| 797 | * are set through {@link SearchForm()}. |
||
| 798 | * |
||
| 799 | * @param array $params Unsanitised request parameters |
||
| 800 | * @return DataList |
||
| 801 | */ |
||
| 802 | protected function getList($params = array()) |
||
| 863 | |||
| 864 | /** |
||
| 865 | * Action handler for adding pages to a campaign |
||
| 866 | * |
||
| 867 | * @param array $data |
||
| 868 | * @param Form $form |
||
| 869 | * @return DBHTMLText|HTTPResponse |
||
| 870 | */ |
||
| 871 | public function addtocampaign($data, $form) |
||
| 891 | |||
| 892 | /** |
||
| 893 | * Url handler for add to campaign form |
||
| 894 | * |
||
| 895 | * @param HTTPRequest $request |
||
| 896 | * @return Form |
||
| 897 | */ |
||
| 898 | public function addToCampaignForm($request) |
||
| 904 | |||
| 905 | /** |
||
| 906 | * @param int $id |
||
| 907 | * @return Form |
||
| 908 | */ |
||
| 909 | public function getAddToCampaignForm($id) |
||
| 936 | |||
| 937 | /** |
||
| 938 | * @return Upload |
||
| 939 | */ |
||
| 940 | protected function getUpload() |
||
| 950 | |||
| 951 | /** |
||
| 952 | * Get actions for file edit |
||
| 953 | * |
||
| 954 | * @param File $file |
||
| 955 | * @return FieldList |
||
| 956 | */ |
||
| 957 | protected function getFileEditActions($file) |
||
| 1021 | } |
||
| 1022 |