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 | 'GET api/readFolder' => 'apiReadFolder', |
||
68 | 'PUT api/updateFolder' => 'apiUpdateFolder', |
||
69 | 'DELETE api/delete' => 'apiDelete', |
||
70 | 'GET api/history' => 'apiHistory' |
||
71 | ]; |
||
72 | |||
73 | /** |
||
74 | * Amount of results showing on a single page. |
||
75 | * |
||
76 | * @config |
||
77 | * @var int |
||
78 | */ |
||
79 | private static $page_length = 15; |
||
80 | |||
81 | /** |
||
82 | * @config |
||
83 | * @see Upload->allowedMaxFileSize |
||
84 | * @var int |
||
85 | */ |
||
86 | private static $allowed_max_file_size; |
||
87 | |||
88 | /** |
||
89 | * @config |
||
90 | * |
||
91 | * @var int |
||
92 | */ |
||
93 | private static $max_history_entries = 100; |
||
94 | |||
95 | /** |
||
96 | * @var array |
||
97 | */ |
||
98 | private static $allowed_actions = array( |
||
99 | 'legacyRedirectForEditView', |
||
100 | 'apiCreateFolder', |
||
101 | 'apiCreateFile', |
||
102 | 'apiReadFolder', |
||
103 | 'apiUpdateFolder', |
||
104 | 'apiHistory', |
||
105 | 'apiDelete', |
||
106 | 'fileEditForm', |
||
107 | 'fileHistoryForm', |
||
108 | 'addToCampaignForm', |
||
109 | 'fileInsertForm', |
||
110 | 'schema', |
||
111 | 'fileSelectForm', |
||
112 | 'fileSearchForm', |
||
113 | ); |
||
114 | |||
115 | private static $required_permission_codes = 'CMS_ACCESS_AssetAdmin'; |
||
116 | |||
117 | private static $thumbnail_width = 400; |
||
118 | |||
119 | private static $thumbnail_height = 300; |
||
120 | |||
121 | /** |
||
122 | * Set up the controller |
||
123 | */ |
||
124 | public function init() |
||
134 | |||
135 | public function getClientConfig() |
||
193 | |||
194 | /** |
||
195 | * Fetches a collection of files by ParentID. |
||
196 | * |
||
197 | * @param HTTPRequest $request |
||
198 | * @return HTTPResponse |
||
199 | */ |
||
200 | public function apiReadFolder(HTTPRequest $request) |
||
201 | { |
||
202 | $params = $request->requestVars(); |
||
203 | $items = array(); |
||
204 | $parentId = null; |
||
205 | $folderID = null; |
||
206 | $query = isset($params['search']) ? $params['search'] : []; |
||
207 | |||
208 | if (!isset($params['id']) && !strlen($params['id'])) { |
||
209 | $this->httpError(400); |
||
210 | } |
||
211 | |||
212 | $folderID = (int)$params['id']; |
||
213 | /** @var Folder $folder */ |
||
214 | $folder = $folderID ? Folder::get()->byID($folderID) : Folder::singleton(); |
||
215 | |||
216 | if (!$folder) { |
||
217 | $this->httpError(400); |
||
218 | } |
||
219 | |||
220 | // TODO Limit results to avoid running out of memory (implement client-side pagination) |
||
221 | if (empty($query['AllFolders'])) { |
||
222 | $query['ParentID'] = $folderID; |
||
223 | } else { |
||
224 | unset($query['AllFolders']); |
||
225 | } |
||
226 | $files = $this->getList($query); |
||
227 | |||
228 | if ($files) { |
||
229 | /** @var File $file */ |
||
230 | foreach ($files as $file) { |
||
231 | if (!$file->canView()) { |
||
232 | continue; |
||
233 | } |
||
234 | |||
235 | $items[] = $this->getObjectFromData($file); |
||
236 | } |
||
237 | } |
||
238 | |||
239 | // Build parents (for breadcrumbs) |
||
240 | $parents = []; |
||
241 | $next = $folder->Parent(); |
||
242 | while ($next && $next->exists()) { |
||
243 | array_unshift($parents, [ |
||
244 | 'id' => $next->ID, |
||
245 | 'title' => $next->getTitle(), |
||
246 | 'filename' => $next->getFilename(), |
||
247 | ]); |
||
248 | if ($next->ParentID) { |
||
249 | $next = $next->Parent(); |
||
250 | } else { |
||
251 | break; |
||
252 | } |
||
253 | } |
||
254 | |||
255 | $column = 'title'; |
||
256 | $direction = 'asc'; |
||
257 | if (isset($params['sort'])) { |
||
258 | list($column, $direction) = explode(',', $params['sort']); |
||
259 | } |
||
260 | $multiplier = ($direction === 'asc') ? 1 : -1; |
||
261 | |||
262 | usort($items, function ($a, $b) use ($column, $multiplier) { |
||
263 | if (!isset($a[$column]) || !isset($b[$column])) { |
||
264 | return 0; |
||
265 | } |
||
266 | if ($a['type'] === 'folder' && $b['type'] !== 'folder') { |
||
267 | return -1; |
||
268 | } |
||
269 | if ($b['type'] === 'folder' && $a['type'] !== 'folder') { |
||
270 | return 1; |
||
271 | } |
||
272 | $numeric = (is_numeric($a[$column]) && is_numeric($b[$column])); |
||
273 | $fieldA = ($numeric) ? floatval($a[$column]) : strtolower($a[$column]); |
||
274 | $fieldB = ($numeric) ? floatval($b[$column]) : strtolower($b[$column]); |
||
275 | |||
276 | if ($fieldA < $fieldB) { |
||
277 | return $multiplier * -1; |
||
278 | } |
||
279 | |||
280 | if ($fieldA > $fieldB) { |
||
281 | return $multiplier; |
||
282 | } |
||
283 | |||
284 | return 0; |
||
285 | }); |
||
286 | |||
287 | $page = (isset($params['page'])) ? $params['page'] : 0; |
||
288 | $limit = (isset($params['limit'])) ? $params['limit'] : $this->config()->page_length; |
||
289 | $filteredItems = array_slice($items, $page * $limit, $limit); |
||
290 | |||
291 | // Build response |
||
292 | $response = new HTTPResponse(); |
||
293 | $response->addHeader('Content-Type', 'application/json'); |
||
294 | $response->setBody(json_encode([ |
||
295 | 'files' => $filteredItems, |
||
296 | 'title' => $folder->getTitle(), |
||
297 | 'count' => count($items), |
||
298 | 'parents' => $parents, |
||
299 | 'parent' => $parents ? $parents[count($parents) - 1] : null, |
||
300 | 'parentID' => $folder->exists() ? $folder->ParentID : null, // grandparent |
||
301 | 'folderID' => $folderID, |
||
302 | 'canEdit' => $folder->canEdit(), |
||
303 | 'canDelete' => $folder->canArchive(), |
||
304 | ])); |
||
305 | |||
306 | return $response; |
||
307 | } |
||
308 | |||
309 | /** |
||
310 | * @param HTTPRequest $request |
||
311 | * |
||
312 | * @return HTTPResponse |
||
313 | */ |
||
314 | public function apiDelete(HTTPRequest $request) |
||
315 | { |
||
316 | parse_str($request->getBody(), $vars); |
||
317 | |||
318 | // CSRF check |
||
319 | $token = SecurityToken::inst(); |
||
320 | View Code Duplication | if (empty($vars[$token->getName()]) || !$token->check($vars[$token->getName()])) { |
|
321 | return new HTTPResponse(null, 400); |
||
322 | } |
||
323 | |||
324 | View Code Duplication | if (!isset($vars['ids']) || !$vars['ids']) { |
|
325 | return (new HTTPResponse(json_encode(['status' => 'error']), 400)) |
||
326 | ->addHeader('Content-Type', 'application/json'); |
||
327 | } |
||
328 | |||
329 | $fileIds = $vars['ids']; |
||
330 | $files = $this->getList()->filter("ID", $fileIds)->toArray(); |
||
331 | |||
332 | View Code Duplication | if (!count($files)) { |
|
333 | return (new HTTPResponse(json_encode(['status' => 'error']), 404)) |
||
334 | ->addHeader('Content-Type', 'application/json'); |
||
335 | } |
||
336 | |||
337 | if (!min(array_map(function (File $file) { |
||
338 | return $file->canArchive(); |
||
339 | }, $files))) { |
||
340 | return (new HTTPResponse(json_encode(['status' => 'error']), 401)) |
||
341 | ->addHeader('Content-Type', 'application/json'); |
||
342 | } |
||
343 | |||
344 | /** @var File $file */ |
||
345 | foreach ($files as $file) { |
||
346 | $file->doArchive(); |
||
347 | } |
||
348 | |||
349 | return (new HTTPResponse(json_encode(['status' => 'file was deleted']))) |
||
350 | ->addHeader('Content-Type', 'application/json'); |
||
351 | } |
||
352 | |||
353 | /** |
||
354 | * Creates a single file based on a form-urlencoded upload. |
||
355 | * |
||
356 | * @param HTTPRequest $request |
||
357 | * @return HTTPRequest|HTTPResponse |
||
358 | */ |
||
359 | public function apiCreateFile(HTTPRequest $request) |
||
431 | |||
432 | /** |
||
433 | * Returns a JSON array for history of a given file ID. Returns a list of all the history. |
||
434 | * |
||
435 | * @param HTTPRequest $request |
||
436 | * @return HTTPResponse |
||
437 | */ |
||
438 | public function apiHistory(HTTPRequest $request) |
||
526 | |||
527 | |||
528 | /** |
||
529 | * Creates a single folder, within an optional parent folder. |
||
530 | * |
||
531 | * @param HTTPRequest $request |
||
532 | * @return HTTPRequest|HTTPResponse |
||
533 | */ |
||
534 | public function apiCreateFolder(HTTPRequest $request) |
||
535 | { |
||
536 | $data = $request->postVars(); |
||
537 | |||
538 | $class = 'SilverStripe\\Assets\\Folder'; |
||
539 | |||
540 | // CSRF check |
||
541 | $token = SecurityToken::inst(); |
||
542 | View Code Duplication | if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) { |
|
543 | return new HTTPResponse(null, 400); |
||
544 | } |
||
545 | |||
546 | // check addchildren permissions |
||
547 | /** @var Folder $parentRecord */ |
||
548 | $parentRecord = null; |
||
549 | if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) { |
||
550 | $parentRecord = DataObject::get_by_id($class, $data['ParentID']); |
||
551 | } |
||
552 | $data['Parent'] = $parentRecord; |
||
553 | $data['ParentID'] = $parentRecord ? (int)$parentRecord->ID : 0; |
||
554 | |||
555 | // Build filename |
||
556 | $baseFilename = isset($data['Name']) |
||
557 | ? basename($data['Name']) |
||
558 | : _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.NEWFOLDER', "NewFolder"); |
||
559 | |||
560 | if ($parentRecord && $parentRecord->ID) { |
||
561 | $baseFilename = $parentRecord->getFilename() . '/' . $baseFilename; |
||
562 | } |
||
563 | |||
564 | // Ensure name is unique |
||
565 | $nameGenerator = $this->getNameGenerator($baseFilename); |
||
566 | $filename = null; |
||
567 | foreach ($nameGenerator as $filename) { |
||
568 | if (! File::find($filename)) { |
||
569 | break; |
||
570 | } |
||
571 | } |
||
572 | $data['Name'] = basename($filename); |
||
573 | |||
574 | // Create record |
||
575 | /** @var Folder $record */ |
||
576 | $record = Injector::inst()->create($class); |
||
577 | |||
578 | // check create permissions |
||
579 | if (!$record->canCreate(null, $data)) { |
||
580 | return (new HTTPResponse(null, 403)) |
||
581 | ->addHeader('Content-Type', 'application/json'); |
||
582 | } |
||
583 | |||
584 | $record->ParentID = $data['ParentID']; |
||
585 | $record->Name = $record->Title = basename($data['Name']); |
||
586 | $record->write(); |
||
587 | |||
588 | $result = $this->getObjectFromData($record); |
||
589 | |||
590 | return (new HTTPResponse(json_encode($result)))->addHeader('Content-Type', 'application/json'); |
||
591 | } |
||
592 | |||
593 | /** |
||
594 | * Redirects 3.x style detail links to new 4.x style routing. |
||
595 | * |
||
596 | * @param HTTPRequest $request |
||
597 | */ |
||
598 | public function legacyRedirectForEditView($request) |
||
606 | |||
607 | /** |
||
608 | * Given a file return the CMS link to edit it |
||
609 | * |
||
610 | * @param File $file |
||
611 | * @return string |
||
612 | */ |
||
613 | public function getFileEditLink($file) |
||
626 | |||
627 | /** |
||
628 | * Get an asset renamer for the given filename. |
||
629 | * |
||
630 | * @param string $filename Path name |
||
631 | * @return AssetNameGenerator |
||
632 | */ |
||
633 | protected function getNameGenerator($filename) |
||
638 | |||
639 | /** |
||
640 | * @todo Implement on client |
||
641 | * |
||
642 | * @param bool $unlinked |
||
643 | * @return ArrayList |
||
644 | */ |
||
645 | public function breadcrumbs($unlinked = false) |
||
649 | |||
650 | |||
651 | /** |
||
652 | * Don't include class namespace in auto-generated CSS class |
||
653 | */ |
||
654 | public function baseCSSClasses() |
||
658 | |||
659 | public function providePermissions() |
||
660 | { |
||
661 | return array( |
||
662 | "CMS_ACCESS_AssetAdmin" => array( |
||
663 | 'name' => _t('CMSMain.ACCESS', "Access to '{title}' section", array( |
||
664 | 'title' => static::menu_title() |
||
665 | )), |
||
666 | 'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access') |
||
667 | ) |
||
668 | ); |
||
669 | } |
||
670 | |||
671 | /** |
||
672 | * Build a form scaffolder for this model |
||
673 | * |
||
674 | * NOTE: Volatile api. May be moved to {@see LeftAndMain} |
||
675 | * |
||
676 | * @param File $file |
||
677 | * @return FormFactory |
||
678 | */ |
||
679 | public function getFormFactory(File $file) |
||
692 | |||
693 | /** |
||
694 | * The form is used to generate a form schema, |
||
695 | * as well as an intermediary object to process data through API endpoints. |
||
696 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
697 | * It handles both {@link File} and {@link Folder} records. |
||
698 | * |
||
699 | * @param int $id |
||
700 | * @return Form |
||
701 | */ |
||
702 | public function getFileEditForm($id) |
||
703 | { |
||
704 | return $this->getAbstractFileForm($id, 'fileEditForm'); |
||
705 | } |
||
706 | |||
707 | /** |
||
708 | * Get file edit form |
||
709 | * |
||
710 | * @return Form |
||
711 | */ |
||
712 | View Code Duplication | public function fileEditForm() |
|
719 | |||
720 | /** |
||
721 | * The form is used to generate a form schema, |
||
722 | * as well as an intermediary object to process data through API endpoints. |
||
723 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
724 | * It handles both {@link File} and {@link Folder} records. |
||
725 | * |
||
726 | * @param int $id |
||
727 | * @return Form |
||
728 | */ |
||
729 | public function getFileInsertForm($id) |
||
733 | |||
734 | /** |
||
735 | * Get file insert form |
||
736 | * |
||
737 | * @return Form |
||
738 | */ |
||
739 | View Code Duplication | public function fileInsertForm() |
|
746 | |||
747 | /** |
||
748 | * Abstract method for generating a form for a file |
||
749 | * |
||
750 | * @param int $id Record ID |
||
751 | * @param string $name Form name |
||
752 | * @param array $context Form context |
||
753 | * @return Form |
||
754 | */ |
||
755 | protected function getAbstractFileForm($id, $name, $context = []) |
||
784 | |||
785 | /** |
||
786 | * Get form for selecting a file |
||
787 | * |
||
788 | * @return Form |
||
789 | */ |
||
790 | public function fileSelectForm() |
||
797 | |||
798 | /** |
||
799 | * Get form for selecting a file |
||
800 | * |
||
801 | * @param int $id ID of the record being selected |
||
802 | * @return Form |
||
803 | */ |
||
804 | public function getFileSelectForm($id) |
||
808 | |||
809 | /** |
||
810 | * @param array $context |
||
811 | * @return Form |
||
812 | * @throws InvalidArgumentException |
||
813 | */ |
||
814 | public function getFileHistoryForm($context) |
||
856 | |||
857 | /** |
||
858 | * Gets a JSON schema representing the current edit form. |
||
859 | * |
||
860 | * WARNING: Experimental API. |
||
861 | * |
||
862 | * @param HTTPRequest $request |
||
863 | * @return HTTPResponse |
||
864 | */ |
||
865 | public function schema($request) |
||
888 | |||
889 | /** |
||
890 | * Get file history form |
||
891 | * |
||
892 | * @return Form |
||
893 | */ |
||
894 | public function fileHistoryForm() |
||
905 | |||
906 | /** |
||
907 | * @param array $data |
||
908 | * @param Form $form |
||
909 | * @return HTTPResponse |
||
910 | */ |
||
911 | public function save($data, $form) |
||
915 | |||
916 | /** |
||
917 | * @param array $data |
||
918 | * @param Form $form |
||
919 | * @return HTTPResponse |
||
920 | */ |
||
921 | public function publish($data, $form) |
||
925 | |||
926 | /** |
||
927 | * Update thisrecord |
||
928 | * |
||
929 | * @param array $data |
||
930 | * @param Form $form |
||
931 | * @param bool $doPublish |
||
932 | * @return HTTPResponse |
||
933 | */ |
||
934 | protected function saveOrPublish($data, $form, $doPublish = false) |
||
966 | |||
967 | public function unpublish($data, $form) |
||
991 | |||
992 | /** |
||
993 | * @param File $file |
||
994 | * |
||
995 | * @return array |
||
996 | */ |
||
997 | public function getObjectFromData(File $file) |
||
1067 | |||
1068 | /** |
||
1069 | * Returns the files and subfolders contained in the currently selected folder, |
||
1070 | * defaulting to the root node. Doubles as search results, if any search parameters |
||
1071 | * are set through {@link SearchForm()}. |
||
1072 | * |
||
1073 | * @param array $params Unsanitised request parameters |
||
1074 | * @return DataList |
||
1075 | */ |
||
1076 | protected function getList($params = array()) |
||
1077 | { |
||
1078 | /** @var DataList $list */ |
||
1079 | $list = File::get(); |
||
1080 | |||
1081 | // Re-add previously removed "Name" filter as combined filter |
||
1082 | if (!empty($params['Name'])) { |
||
1083 | $list = $list->filterAny(array( |
||
1084 | 'Name:PartialMatch' => $params['Name'], |
||
1085 | 'Title:PartialMatch' => $params['Name'] |
||
1086 | )); |
||
1087 | } |
||
1088 | |||
1089 | // Optionally limit search to a folder (non-recursive) |
||
1090 | if (isset($params['ParentID']) && is_numeric($params['ParentID'])) { |
||
1091 | $list = $list->filter('ParentID', $params['ParentID']); |
||
1092 | } |
||
1093 | |||
1094 | // Date filtering |
||
1095 | View Code Duplication | if (!empty($params['CreatedFrom'])) { |
|
1096 | $fromDate = new DateField(null, null, $params['CreatedFrom']); |
||
1097 | $list = $list->filter("Created:GreaterThanOrEqual", $fromDate->dataValue().' 00:00:00'); |
||
1098 | } |
||
1099 | View Code Duplication | if (!empty($params['CreatedTo'])) { |
|
1100 | $toDate = new DateField(null, null, $params['CreatedTo']); |
||
1101 | $list = $list->filter("Created:LessThanOrEqual", $toDate->dataValue().' 23:59:59'); |
||
1102 | } |
||
1103 | |||
1104 | // Categories |
||
1105 | $categories = File::config()->app_categories; |
||
1106 | if (!empty($filters['AppCategory']) && !empty($categories[$filters['AppCategory']])) { |
||
1107 | $extensions = $categories[$filters['AppCategory']]; |
||
1108 | $list = $list->filter('Name:EndsWith', $extensions); |
||
1109 | } |
||
1110 | |||
1111 | // Sort folders first |
||
1112 | $list = $list->sort( |
||
1113 | '(CASE WHEN "File"."ClassName" = \'Folder\' THEN 0 ELSE 1 END), "Name"' |
||
1114 | ); |
||
1115 | |||
1116 | // Pagination |
||
1117 | if (isset($filters['page']) && isset($filters['limit'])) { |
||
1118 | $page = $filters['page']; |
||
1119 | $limit = $filters['limit']; |
||
1120 | $offset = ($page - 1) * $limit; |
||
1121 | $list = $list->limit($limit, $offset); |
||
1122 | } |
||
1123 | |||
1124 | // Access checks |
||
1125 | $list = $list->filterByCallback(function (File $file) { |
||
1126 | return $file->canView(); |
||
1127 | }); |
||
1128 | |||
1129 | return $list; |
||
1130 | } |
||
1131 | |||
1132 | /** |
||
1133 | * Action handler for adding pages to a campaign |
||
1134 | * |
||
1135 | * @param array $data |
||
1136 | * @param Form $form |
||
1137 | * @return DBHTMLText|HTTPResponse |
||
1138 | */ |
||
1139 | public function addtocampaign($data, $form) |
||
1155 | |||
1156 | /** |
||
1157 | * Url handler for add to campaign form |
||
1158 | * |
||
1159 | * @param HTTPRequest $request |
||
1160 | * @return Form |
||
1161 | */ |
||
1162 | public function addToCampaignForm($request) |
||
1168 | |||
1169 | /** |
||
1170 | * @param int $id |
||
1171 | * @return Form |
||
1172 | */ |
||
1173 | public function getAddToCampaignForm($id) |
||
1207 | |||
1208 | /** |
||
1209 | * @return Upload |
||
1210 | */ |
||
1211 | protected function getUpload() |
||
1221 | |||
1222 | /** |
||
1223 | * Get response for successfully updated record |
||
1224 | * |
||
1225 | * @param File $record |
||
1226 | * @param Form $form |
||
1227 | * @return HTTPResponse |
||
1228 | */ |
||
1229 | protected function getRecordUpdatedResponse($record, $form) |
||
1236 | |||
1237 | /** |
||
1238 | * Scaffold a search form. |
||
1239 | * Note: This form does not submit to itself, but rather uses the apiReadFolder endpoint |
||
1240 | * (to be replaced with graphql) |
||
1241 | * |
||
1242 | * @return Form |
||
1243 | */ |
||
1244 | public function fileSearchForm() |
||
1249 | |||
1250 | /** |
||
1251 | * Allow search form to be accessible to schema |
||
1252 | * |
||
1253 | * @return Form |
||
1254 | */ |
||
1255 | public function getFileSearchform() { |
||
1258 | } |
||
1259 |