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 |
||
49 | class AssetAdmin extends LeftAndMain implements PermissionProvider |
||
50 | { |
||
51 | private static $url_segment = 'assets'; |
||
52 | |||
53 | private static $url_rule = '/$Action/$ID'; |
||
54 | |||
55 | private static $menu_title = 'Files'; |
||
56 | |||
57 | private static $tree_class = 'SilverStripe\\Assets\\Folder'; |
||
58 | |||
59 | private static $url_handlers = [ |
||
60 | // Legacy redirect for SS3-style detail view |
||
61 | 'EditForm/field/File/item/$FileID/$Action' => 'legacyRedirectForEditView', |
||
62 | // Pass all URLs to the index, for React to unpack |
||
63 | 'show/$FolderID/edit/$FileID' => 'index', |
||
64 | // API access points with structured data |
||
65 | 'POST api/createFolder' => 'apiCreateFolder', |
||
66 | 'POST api/createFile' => 'apiCreateFile', |
||
67 | 'POST api/uploadFile' => 'apiUploadFile', |
||
68 | 'GET api/readFolder' => 'apiReadFolder', |
||
69 | 'PUT api/updateFolder' => 'apiUpdateFolder', |
||
70 | 'DELETE api/delete' => 'apiDelete', |
||
71 | 'GET api/search' => 'apiSearch', |
||
72 | 'GET api/history' => 'apiHistory' |
||
73 | ]; |
||
74 | |||
75 | /** |
||
76 | * Amount of results showing on a single page. |
||
77 | * |
||
78 | * @config |
||
79 | * @var int |
||
80 | */ |
||
81 | private static $page_length = 15; |
||
82 | |||
83 | /** |
||
84 | * @config |
||
85 | * @see Upload->allowedMaxFileSize |
||
86 | * @var int |
||
87 | */ |
||
88 | private static $allowed_max_file_size; |
||
89 | |||
90 | /** |
||
91 | * @config |
||
92 | * |
||
93 | * @var int |
||
94 | */ |
||
95 | private static $max_history_entries = 100; |
||
96 | |||
97 | /** |
||
98 | * @var array |
||
99 | */ |
||
100 | private static $allowed_actions = array( |
||
101 | 'legacyRedirectForEditView', |
||
102 | 'apiCreateFolder', |
||
103 | 'apiCreateFile', |
||
104 | 'apiUploadFile', |
||
105 | 'apiReadFolder', |
||
106 | 'apiUpdateFolder', |
||
107 | 'apiHistory', |
||
108 | 'apiDelete', |
||
109 | 'apiSearch', |
||
110 | 'fileEditForm', |
||
111 | 'fileHistoryForm', |
||
112 | 'addToCampaignForm', |
||
113 | 'fileInsertForm', |
||
114 | 'schema', |
||
115 | 'fileSelectForm', |
||
116 | ); |
||
117 | |||
118 | private static $required_permission_codes = 'CMS_ACCESS_AssetAdmin'; |
||
119 | |||
120 | private static $thumbnail_width = 400; |
||
121 | |||
122 | private static $thumbnail_height = 300; |
||
123 | |||
124 | /** |
||
125 | * Set up the controller |
||
126 | */ |
||
127 | public function init() |
||
137 | |||
138 | public function getClientConfig() |
||
203 | |||
204 | /** |
||
205 | * Fetches a collection of files by ParentID. |
||
206 | * |
||
207 | * @param HTTPRequest $request |
||
208 | * @return HTTPResponse |
||
209 | */ |
||
210 | public function apiReadFolder(HTTPRequest $request) |
||
312 | |||
313 | /** |
||
314 | * @param HTTPRequest $request |
||
315 | * |
||
316 | * @return HTTPResponse |
||
317 | */ |
||
318 | public function apiSearch(HTTPRequest $request) |
||
335 | |||
336 | /** |
||
337 | * @param HTTPRequest $request |
||
338 | * |
||
339 | * @return HTTPResponse |
||
340 | */ |
||
341 | public function apiDelete(HTTPRequest $request) |
||
379 | |||
380 | /** |
||
381 | * Creates a single file based on a form-urlencoded upload. |
||
382 | * |
||
383 | * @param HTTPRequest $request |
||
384 | * @return HTTPRequest|HTTPResponse |
||
385 | */ |
||
386 | public function apiCreateFile(HTTPRequest $request) |
||
387 | { |
||
388 | $data = $request->postVars(); |
||
389 | $upload = $this->getUpload(); |
||
390 | |||
391 | // CSRF check |
||
392 | $token = SecurityToken::inst(); |
||
393 | View Code Duplication | if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) { |
|
394 | return new HTTPResponse(null, 400); |
||
395 | } |
||
396 | |||
397 | // Check parent record |
||
398 | /** @var Folder $parentRecord */ |
||
399 | $parentRecord = null; |
||
400 | View Code Duplication | if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) { |
|
401 | $parentRecord = Folder::get()->byID($data['ParentID']); |
||
402 | } |
||
403 | $data['Parent'] = $parentRecord; |
||
404 | |||
405 | $tmpFile = $request->postVar('Upload'); |
||
406 | View Code Duplication | if (!$upload->validate($tmpFile)) { |
|
407 | $result = ['message' => null]; |
||
408 | $errors = $upload->getErrors(); |
||
409 | if ($message = array_shift($errors)) { |
||
410 | $result['message'] = [ |
||
411 | 'type' => 'error', |
||
412 | 'value' => $message, |
||
413 | ]; |
||
414 | } |
||
415 | return (new HTTPResponse(json_encode($result), 400)) |
||
416 | ->addHeader('Content-Type', 'application/json'); |
||
417 | } |
||
418 | |||
419 | // TODO Allow batch uploads |
||
420 | $fileClass = File::get_class_for_file_extension(File::get_file_extension($tmpFile['name'])); |
||
421 | /** @var File $file */ |
||
422 | $file = Injector::inst()->create($fileClass); |
||
423 | |||
424 | // check canCreate permissions |
||
425 | View Code Duplication | if (!$file->canCreate(null, $data)) { |
|
426 | $result = ['message' => [ |
||
427 | 'type' => 'error', |
||
428 | 'value' => _t( |
||
429 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.CreatePermissionDenied', |
||
430 | 'You do not have permission to add files' |
||
431 | ) |
||
432 | ]]; |
||
433 | return (new HTTPResponse(json_encode($result), 403)) |
||
434 | ->addHeader('Content-Type', 'application/json'); |
||
435 | } |
||
436 | |||
437 | $uploadResult = $upload->loadIntoFile($tmpFile, $file, $parentRecord ? $parentRecord->getFilename() : '/'); |
||
438 | View Code Duplication | if (!$uploadResult) { |
|
439 | $result = ['message' => [ |
||
440 | 'type' => 'error', |
||
441 | 'value' => _t( |
||
442 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.LoadIntoFileFailed', |
||
443 | 'Failed to load file' |
||
444 | ) |
||
445 | ]]; |
||
446 | return (new HTTPResponse(json_encode($result), 400)) |
||
447 | ->addHeader('Content-Type', 'application/json'); |
||
448 | } |
||
449 | |||
450 | $file->ParentID = $parentRecord ? $parentRecord->ID : 0; |
||
451 | $file->write(); |
||
452 | |||
453 | $result = [$this->getObjectFromData($file)]; |
||
454 | |||
455 | return (new HTTPResponse(json_encode($result))) |
||
456 | ->addHeader('Content-Type', 'application/json'); |
||
457 | } |
||
458 | |||
459 | /** |
||
460 | * Upload a new asset for a pre-existing record. Returns the asset tuple. |
||
461 | * |
||
462 | * @param HTTPRequest $request |
||
463 | * @return HTTPRequest|HTTPResponse |
||
464 | */ |
||
465 | public function apiUploadFile(HTTPRequest $request) |
||
466 | { |
||
467 | $data = $request->postVars(); |
||
468 | $upload = $this->getUpload(); |
||
469 | |||
470 | // CSRF check |
||
471 | $token = SecurityToken::inst(); |
||
472 | View Code Duplication | if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) { |
|
473 | return new HTTPResponse(null, 400); |
||
474 | } |
||
475 | |||
476 | // Check parent record |
||
477 | /** @var Folder $parentRecord */ |
||
478 | $parentRecord = null; |
||
479 | View Code Duplication | if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) { |
|
480 | $parentRecord = Folder::get()->byID($data['ParentID']); |
||
481 | } |
||
482 | |||
483 | $tmpFile = $data['Upload']; |
||
484 | View Code Duplication | if (!$upload->validate($tmpFile)) { |
|
485 | $result = ['message' => null]; |
||
486 | $errors = $upload->getErrors(); |
||
487 | if ($message = array_shift($errors)) { |
||
488 | $result['message'] = [ |
||
489 | 'type' => 'error', |
||
490 | 'value' => $message, |
||
491 | ]; |
||
492 | } |
||
493 | return (new HTTPResponse(json_encode($result), 400)) |
||
494 | ->addHeader('Content-Type', 'application/json'); |
||
495 | } |
||
496 | |||
497 | $folder = $parentRecord ? $parentRecord->getFilename() : '/'; |
||
498 | |||
499 | try { |
||
500 | $tuple = $upload->load($tmpFile, $folder); |
||
501 | } catch (Exception $e) { |
||
502 | $result = [ |
||
503 | 'message' => [ |
||
504 | 'type' => 'error', |
||
505 | 'value' => $e->getMessage(), |
||
506 | ] |
||
507 | ]; |
||
508 | return (new HTTPResponse(json_encode($result), 400)) |
||
509 | ->addHeader('Content-Type', 'application/json'); |
||
510 | } |
||
511 | |||
512 | if ($upload->isError()) { |
||
513 | $result['message'] = [ |
||
514 | 'type' => 'error', |
||
515 | 'value' => implode(' ' . PHP_EOL, $upload->getErrors()), |
||
516 | ]; |
||
517 | return (new HTTPResponse(json_encode($result), 400)) |
||
518 | ->addHeader('Content-Type', 'application/json'); |
||
519 | } |
||
520 | |||
521 | $tuple['Name'] = basename($tuple['Filename']); |
||
522 | return (new HTTPResponse(json_encode($tuple))) |
||
523 | ->addHeader('Content-Type', 'application/json'); |
||
524 | } |
||
525 | |||
526 | /** |
||
527 | * Returns a JSON array for history of a given file ID. Returns a list of all the history. |
||
528 | * |
||
529 | * @param HTTPRequest $request |
||
530 | * @return HTTPResponse |
||
531 | */ |
||
532 | public function apiHistory(HTTPRequest $request) |
||
620 | |||
621 | |||
622 | /** |
||
623 | * Creates a single folder, within an optional parent folder. |
||
624 | * |
||
625 | * @param HTTPRequest $request |
||
626 | * @return HTTPRequest|HTTPResponse |
||
627 | */ |
||
628 | public function apiCreateFolder(HTTPRequest $request) |
||
686 | |||
687 | /** |
||
688 | * Redirects 3.x style detail links to new 4.x style routing. |
||
689 | * |
||
690 | * @param HTTPRequest $request |
||
691 | */ |
||
692 | public function legacyRedirectForEditView($request) |
||
700 | |||
701 | /** |
||
702 | * Given a file return the CMS link to edit it |
||
703 | * |
||
704 | * @param File $file |
||
705 | * @return string |
||
706 | */ |
||
707 | public function getFileEditLink($file) |
||
720 | |||
721 | /** |
||
722 | * Get the search context from {@link File}, used to create the search form |
||
723 | * as well as power the /search API endpoint. |
||
724 | * |
||
725 | * @return SearchContext |
||
726 | */ |
||
727 | public function getSearchContext() |
||
780 | |||
781 | /** |
||
782 | * Get an asset renamer for the given filename. |
||
783 | * |
||
784 | * @param string $filename Path name |
||
785 | * @return AssetNameGenerator |
||
786 | */ |
||
787 | protected function getNameGenerator($filename) |
||
792 | |||
793 | /** |
||
794 | * @todo Implement on client |
||
795 | * |
||
796 | * @param bool $unlinked |
||
797 | * @return ArrayList |
||
798 | */ |
||
799 | public function breadcrumbs($unlinked = false) |
||
803 | |||
804 | |||
805 | /** |
||
806 | * Don't include class namespace in auto-generated CSS class |
||
807 | */ |
||
808 | public function baseCSSClasses() |
||
812 | |||
813 | public function providePermissions() |
||
824 | |||
825 | /** |
||
826 | * Build a form scaffolder for this model |
||
827 | * |
||
828 | * NOTE: Volatile api. May be moved to {@see LeftAndMain} |
||
829 | * |
||
830 | * @param File $file |
||
831 | * @return FormFactory |
||
832 | */ |
||
833 | public function getFormFactory(File $file) |
||
846 | |||
847 | /** |
||
848 | * The form is used to generate a form schema, |
||
849 | * as well as an intermediary object to process data through API endpoints. |
||
850 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
851 | * It handles both {@link File} and {@link Folder} records. |
||
852 | * |
||
853 | * @param int $id |
||
854 | * @return Form |
||
855 | */ |
||
856 | public function getFileEditForm($id) |
||
860 | |||
861 | /** |
||
862 | * Get file edit form |
||
863 | * |
||
864 | * @return Form |
||
865 | */ |
||
866 | View Code Duplication | public function fileEditForm() |
|
873 | |||
874 | /** |
||
875 | * The form is used to generate a form schema, |
||
876 | * as well as an intermediary object to process data through API endpoints. |
||
877 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
878 | * It handles both {@link File} and {@link Folder} records. |
||
879 | * |
||
880 | * @param int $id |
||
881 | * @return Form |
||
882 | */ |
||
883 | public function getFileInsertForm($id) |
||
887 | |||
888 | /** |
||
889 | * Get file insert form |
||
890 | * |
||
891 | * @return Form |
||
892 | */ |
||
893 | View Code Duplication | public function fileInsertForm() |
|
900 | |||
901 | /** |
||
902 | * Abstract method for generating a form for a file |
||
903 | * |
||
904 | * @param int $id Record ID |
||
905 | * @param string $name Form name |
||
906 | * @param array $context Form context |
||
907 | * @return Form |
||
908 | */ |
||
909 | protected function getAbstractFileForm($id, $name, $context = []) |
||
938 | |||
939 | /** |
||
940 | * Get form for selecting a file |
||
941 | * |
||
942 | * @return Form |
||
943 | */ |
||
944 | public function fileSelectForm() |
||
951 | |||
952 | /** |
||
953 | * Get form for selecting a file |
||
954 | * |
||
955 | * @param int $id ID of the record being selected |
||
956 | * @return Form |
||
957 | */ |
||
958 | public function getFileSelectForm($id) |
||
962 | |||
963 | /** |
||
964 | * @param array $context |
||
965 | * @return Form |
||
966 | * @throws InvalidArgumentException |
||
967 | */ |
||
968 | public function getFileHistoryForm($context) |
||
1010 | |||
1011 | /** |
||
1012 | * Gets a JSON schema representing the current edit form. |
||
1013 | * |
||
1014 | * WARNING: Experimental API. |
||
1015 | * |
||
1016 | * @param HTTPRequest $request |
||
1017 | * @return HTTPResponse |
||
1018 | */ |
||
1019 | public function schema($request) |
||
1042 | |||
1043 | /** |
||
1044 | * Get file history form |
||
1045 | * |
||
1046 | * @return Form |
||
1047 | */ |
||
1048 | public function fileHistoryForm() |
||
1059 | |||
1060 | /** |
||
1061 | * @param array $data |
||
1062 | * @param Form $form |
||
1063 | * @return HTTPResponse |
||
1064 | */ |
||
1065 | public function save($data, $form) |
||
1069 | |||
1070 | /** |
||
1071 | * @param array $data |
||
1072 | * @param Form $form |
||
1073 | * @return HTTPResponse |
||
1074 | */ |
||
1075 | public function publish($data, $form) |
||
1079 | |||
1080 | /** |
||
1081 | * Update thisrecord |
||
1082 | * |
||
1083 | * @param array $data |
||
1084 | * @param Form $form |
||
1085 | * @param bool $doPublish |
||
1086 | * @return HTTPResponse |
||
1087 | */ |
||
1088 | protected function saveOrPublish($data, $form, $doPublish = false) |
||
1089 | { |
||
1090 | View Code Duplication | if (!isset($data['ID']) || !is_numeric($data['ID'])) { |
|
1091 | return (new HTTPResponse(json_encode(['status' => 'error']), 400)) |
||
1092 | ->addHeader('Content-Type', 'application/json'); |
||
1093 | } |
||
1094 | |||
1095 | $id = (int) $data['ID']; |
||
1096 | /** @var File $record */ |
||
1097 | $record = DataObject::get_by_id(File::class, $id); |
||
1098 | |||
1099 | View Code Duplication | if (!$record) { |
|
1100 | return (new HTTPResponse(json_encode(['status' => 'error']), 404)) |
||
1101 | ->addHeader('Content-Type', 'application/json'); |
||
1102 | } |
||
1103 | |||
1104 | if (!$record->canEdit() || ($doPublish && !$record->canPublish())) { |
||
1105 | return (new HTTPResponse(json_encode(['status' => 'error']), 401)) |
||
1106 | ->addHeader('Content-Type', 'application/json'); |
||
1107 | } |
||
1108 | |||
1109 | // check File extension |
||
1110 | $extension = File::get_file_extension($data['FileFilename']); |
||
1111 | $newClass = File::get_class_for_file_extension($extension); |
||
1112 | // if the class has changed, cast it to the proper class |
||
1113 | if ($record->getClassName() !== $newClass) { |
||
1114 | $record = $record->newClassInstance($newClass); |
||
1115 | |||
1116 | // update the allowed category for the new file extension |
||
1117 | $category = File::get_app_category($extension); |
||
1118 | $record->File->setAllowedCategories($category); |
||
1119 | } |
||
1120 | |||
1121 | $form->saveInto($record); |
||
1122 | $record->write(); |
||
1123 | |||
1124 | // Publish this record and owned objects |
||
1125 | if ($doPublish) { |
||
1126 | $record->publishRecursive(); |
||
1127 | } |
||
1128 | |||
1129 | // Note: Force return of schema / state in success result |
||
1130 | return $this->getRecordUpdatedResponse($record, $form); |
||
1131 | } |
||
1132 | |||
1133 | public function unpublish($data, $form) |
||
1157 | |||
1158 | /** |
||
1159 | * @param File $file |
||
1160 | * |
||
1161 | * @return array |
||
1162 | */ |
||
1163 | public function getObjectFromData(File $file) |
||
1233 | |||
1234 | /** |
||
1235 | * Returns the files and subfolders contained in the currently selected folder, |
||
1236 | * defaulting to the root node. Doubles as search results, if any search parameters |
||
1237 | * are set through {@link SearchForm()}. |
||
1238 | * |
||
1239 | * @param array $params Unsanitised request parameters |
||
1240 | * @return DataList |
||
1241 | */ |
||
1242 | protected function getList($params = array()) |
||
1303 | |||
1304 | /** |
||
1305 | * Action handler for adding pages to a campaign |
||
1306 | * |
||
1307 | * @param array $data |
||
1308 | * @param Form $form |
||
1309 | * @return DBHTMLText|HTTPResponse |
||
1310 | */ |
||
1311 | public function addtocampaign($data, $form) |
||
1327 | |||
1328 | /** |
||
1329 | * Url handler for add to campaign form |
||
1330 | * |
||
1331 | * @param HTTPRequest $request |
||
1332 | * @return Form |
||
1333 | */ |
||
1334 | public function addToCampaignForm($request) |
||
1340 | |||
1341 | /** |
||
1342 | * @param int $id |
||
1343 | * @return Form |
||
1344 | */ |
||
1345 | public function getAddToCampaignForm($id) |
||
1379 | |||
1380 | /** |
||
1381 | * @return Upload |
||
1382 | */ |
||
1383 | protected function getUpload() |
||
1393 | |||
1394 | /** |
||
1395 | * Get response for successfully updated record |
||
1396 | * |
||
1397 | * @param File $record |
||
1398 | * @param Form $form |
||
1399 | * @return HTTPResponse |
||
1400 | */ |
||
1401 | protected function getRecordUpdatedResponse($record, $form) |
||
1408 | } |
||
1409 |