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) { |
||
462 | |||
463 | /** |
||
464 | * Get the search context from {@link File}, used to create the search form |
||
465 | * as well as power the /search API endpoint. |
||
466 | * |
||
467 | * @return SearchContext |
||
468 | */ |
||
469 | public function getSearchContext() |
||
521 | |||
522 | /** |
||
523 | * Get an asset renamer for the given filename. |
||
524 | * |
||
525 | * @param string $filename Path name |
||
526 | * @return AssetNameGenerator |
||
527 | */ |
||
528 | protected function getNameGenerator($filename) |
||
533 | |||
534 | /** |
||
535 | * @todo Implement on client |
||
536 | * |
||
537 | * @param bool $unlinked |
||
538 | * @return ArrayList |
||
539 | */ |
||
540 | public function breadcrumbs($unlinked = false) |
||
544 | |||
545 | |||
546 | /** |
||
547 | * Don't include class namespace in auto-generated CSS class |
||
548 | */ |
||
549 | public function baseCSSClasses() |
||
553 | |||
554 | public function providePermissions() |
||
565 | |||
566 | /** |
||
567 | * The form is used to generate a form schema, |
||
568 | * as well as an intermediary object to process data through API endpoints. |
||
569 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
570 | * It handles both {@link File} and {@link Folder} records. |
||
571 | * |
||
572 | * @param int $id |
||
573 | * @return Form |
||
574 | */ |
||
575 | public function getFileEditForm($id) |
||
614 | |||
615 | /** |
||
616 | * Get file edit form |
||
617 | * |
||
618 | * @return Form |
||
619 | */ |
||
620 | public function FileEditForm() |
||
627 | |||
628 | /** |
||
629 | * @param array $data |
||
630 | * @param Form $form |
||
631 | * @return HTTPResponse |
||
632 | */ |
||
633 | public function save($data, $form) |
||
637 | |||
638 | |||
639 | /** |
||
640 | * @param array $data |
||
641 | * @param Form $form |
||
642 | * @return HTTPResponse |
||
643 | */ |
||
644 | public function publish($data, $form) { |
||
647 | |||
648 | /** |
||
649 | * Update thisrecord |
||
650 | * |
||
651 | * @param array $data |
||
652 | * @param Form $form |
||
653 | * @param bool $doPublish |
||
654 | * @return HTTPResponse |
||
655 | */ |
||
656 | protected function saveOrPublish($data, $form, $doPublish = false) { |
||
691 | |||
692 | public function unpublish($data, $form) { |
||
721 | |||
722 | /** |
||
723 | * @param File $file |
||
724 | * |
||
725 | * @return array |
||
726 | */ |
||
727 | protected function getObjectFromData(File $file) |
||
787 | |||
788 | |||
789 | /** |
||
790 | * Returns the files and subfolders contained in the currently selected folder, |
||
791 | * defaulting to the root node. Doubles as search results, if any search parameters |
||
792 | * are set through {@link SearchForm()}. |
||
793 | * |
||
794 | * @param array $params Unsanitised request parameters |
||
795 | * @return DataList |
||
796 | */ |
||
797 | protected function getList($params = array()) |
||
858 | |||
859 | /** |
||
860 | * Action handler for adding pages to a campaign |
||
861 | * |
||
862 | * @param array $data |
||
863 | * @param Form $form |
||
864 | * @return DBHTMLText|HTTPResponse |
||
865 | */ |
||
866 | public function addtocampaign($data, $form) |
||
886 | |||
887 | /** |
||
888 | * Url handler for add to campaign form |
||
889 | * |
||
890 | * @param HTTPRequest $request |
||
891 | * @return Form |
||
892 | */ |
||
893 | public function AddToCampaignForm($request) |
||
899 | |||
900 | /** |
||
901 | * @param int $id |
||
902 | * @return Form |
||
903 | */ |
||
904 | public function getAddToCampaignForm($id) |
||
931 | |||
932 | /** |
||
933 | * @return Upload |
||
934 | */ |
||
935 | protected function getUpload() |
||
945 | |||
946 | /** |
||
947 | * Get actions for file edit |
||
948 | * |
||
949 | * @param File $file |
||
950 | * @return FieldList |
||
951 | */ |
||
952 | protected function getFileEditActions($file) |
||
1016 | } |
||
1017 |