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/createFile' => 'apiCreateFile', |
||
| 66 | 'POST api/uploadFile' => 'apiUploadFile', |
||
| 67 | 'GET api/history' => 'apiHistory' |
||
| 68 | ]; |
||
| 69 | |||
| 70 | /** |
||
| 71 | * Amount of results showing on a single page. |
||
| 72 | * |
||
| 73 | * @config |
||
| 74 | * @var int |
||
| 75 | */ |
||
| 76 | private static $page_length = 15; |
||
| 77 | |||
| 78 | /** |
||
| 79 | * @config |
||
| 80 | * @see Upload->allowedMaxFileSize |
||
| 81 | * @var int |
||
| 82 | */ |
||
| 83 | private static $allowed_max_file_size; |
||
| 84 | |||
| 85 | /** |
||
| 86 | * @config |
||
| 87 | * |
||
| 88 | * @var int |
||
| 89 | */ |
||
| 90 | private static $max_history_entries = 100; |
||
| 91 | |||
| 92 | /** |
||
| 93 | * @var array |
||
| 94 | */ |
||
| 95 | private static $allowed_actions = array( |
||
| 96 | 'legacyRedirectForEditView', |
||
| 97 | 'apiCreateFile', |
||
| 98 | 'apiUploadFile', |
||
| 99 | 'apiHistory', |
||
| 100 | 'fileEditForm', |
||
| 101 | 'fileHistoryForm', |
||
| 102 | 'addToCampaignForm', |
||
| 103 | 'fileInsertForm', |
||
| 104 | 'schema', |
||
| 105 | 'fileSelectForm', |
||
| 106 | ); |
||
| 107 | |||
| 108 | private static $required_permission_codes = 'CMS_ACCESS_AssetAdmin'; |
||
| 109 | |||
| 110 | private static $thumbnail_width = 400; |
||
| 111 | |||
| 112 | private static $thumbnail_height = 300; |
||
| 113 | |||
| 114 | /** |
||
| 115 | * Set up the controller |
||
| 116 | */ |
||
| 117 | public function init() |
||
| 127 | |||
| 128 | public function getClientConfig() |
||
| 168 | |||
| 169 | /** |
||
| 170 | * Creates a single file based on a form-urlencoded upload. |
||
| 171 | * |
||
| 172 | * @param HTTPRequest $request |
||
| 173 | * @return HTTPRequest|HTTPResponse |
||
| 174 | */ |
||
| 175 | public function apiCreateFile(HTTPRequest $request) |
||
| 247 | |||
| 248 | /** |
||
| 249 | * Upload a new asset for a pre-existing record. Returns the asset tuple. |
||
| 250 | * |
||
| 251 | * @param HTTPRequest $request |
||
| 252 | * @return HTTPRequest|HTTPResponse |
||
| 253 | */ |
||
| 254 | public function apiUploadFile(HTTPRequest $request) |
||
| 314 | |||
| 315 | /** |
||
| 316 | * Returns a JSON array for history of a given file ID. Returns a list of all the history. |
||
| 317 | * |
||
| 318 | * @param HTTPRequest $request |
||
| 319 | * @return HTTPResponse |
||
| 320 | */ |
||
| 321 | public function apiHistory(HTTPRequest $request) |
||
| 409 | |||
| 410 | /** |
||
| 411 | * Redirects 3.x style detail links to new 4.x style routing. |
||
| 412 | * |
||
| 413 | * @param HTTPRequest $request |
||
| 414 | */ |
||
| 415 | public function legacyRedirectForEditView($request) |
||
| 423 | |||
| 424 | /** |
||
| 425 | * Given a file return the CMS link to edit it |
||
| 426 | * |
||
| 427 | * @param File $file |
||
| 428 | * @return string |
||
| 429 | */ |
||
| 430 | public function getFileEditLink($file) |
||
| 443 | |||
| 444 | /** |
||
| 445 | * Get the search context from {@link File}, used to create the search form |
||
| 446 | * as well as power the /search API endpoint. |
||
| 447 | * |
||
| 448 | * @return SearchContext |
||
| 449 | */ |
||
| 450 | public function getSearchContext() |
||
| 451 | { |
||
| 452 | $context = File::singleton()->getDefaultSearchContext(); |
||
| 453 | |||
| 454 | // Customize fields |
||
| 455 | $dateHeader = HeaderField::create('Date', _t('CMSSearch.FILTERDATEHEADING', 'Date'), 4); |
||
| 456 | $dateFrom = DateField::create('CreatedFrom', _t('CMSSearch.FILTERDATEFROM', 'From')) |
||
| 457 | ->setConfig('showcalendar', true); |
||
| 458 | $dateTo = DateField::create('CreatedTo', _t('CMSSearch.FILTERDATETO', 'To')) |
||
| 459 | ->setConfig('showcalendar', true); |
||
| 460 | $dateGroup = FieldGroup::create( |
||
| 461 | $dateHeader, |
||
| 462 | $dateFrom, |
||
| 463 | $dateTo |
||
| 464 | ); |
||
| 465 | $context->addField($dateGroup); |
||
| 466 | /** @skipUpgrade */ |
||
| 467 | $appCategories = array( |
||
| 468 | 'archive' => _t( |
||
| 469 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryArchive', |
||
| 470 | 'Archive' |
||
| 471 | ), |
||
| 472 | 'audio' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryAudio', 'Audio'), |
||
| 473 | 'document' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryDocument', 'Document'), |
||
| 474 | 'flash' => _t( |
||
| 475 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryFlash', |
||
| 476 | 'Flash', |
||
| 477 | 'The fileformat' |
||
| 478 | ), |
||
| 479 | 'image' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryImage', 'Image'), |
||
| 480 | 'video' => _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.AppCategoryVideo', 'Video'), |
||
| 481 | ); |
||
| 482 | $context->addField( |
||
| 483 | $typeDropdown = new DropdownField( |
||
| 484 | 'AppCategory', |
||
| 485 | _t('SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.Filetype', 'File type'), |
||
| 486 | $appCategories |
||
| 487 | ) |
||
| 488 | ); |
||
| 489 | |||
| 490 | $typeDropdown->setEmptyString(' '); |
||
| 491 | |||
| 492 | $currentfolderLabel = _t( |
||
| 493 | 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin.CurrentFolderOnly', |
||
| 494 | 'Limit to current folder?' |
||
| 495 | ); |
||
| 496 | $context->addField( |
||
| 497 | new CheckboxField('CurrentFolderOnly', $currentfolderLabel) |
||
| 498 | ); |
||
| 499 | $context->getFields()->removeByName('Title'); |
||
| 500 | |||
| 501 | return $context; |
||
| 502 | } |
||
| 503 | |||
| 504 | /** |
||
| 505 | * Get an asset renamer for the given filename. |
||
| 506 | * |
||
| 507 | * @param string $filename Path name |
||
| 508 | * @return AssetNameGenerator |
||
| 509 | */ |
||
| 510 | protected function getNameGenerator($filename) |
||
| 515 | |||
| 516 | /** |
||
| 517 | * @todo Implement on client |
||
| 518 | * |
||
| 519 | * @param bool $unlinked |
||
| 520 | * @return ArrayList |
||
| 521 | */ |
||
| 522 | public function breadcrumbs($unlinked = false) |
||
| 526 | |||
| 527 | |||
| 528 | /** |
||
| 529 | * Don't include class namespace in auto-generated CSS class |
||
| 530 | */ |
||
| 531 | public function baseCSSClasses() |
||
| 535 | |||
| 536 | public function providePermissions() |
||
| 537 | { |
||
| 538 | return array( |
||
| 539 | "CMS_ACCESS_AssetAdmin" => array( |
||
| 540 | 'name' => _t('CMSMain.ACCESS', "Access to '{title}' section", array( |
||
| 541 | 'title' => static::menu_title() |
||
| 542 | )), |
||
| 543 | 'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access') |
||
| 544 | ) |
||
| 545 | ); |
||
| 546 | } |
||
| 547 | |||
| 548 | /** |
||
| 549 | * Build a form scaffolder for this model |
||
| 550 | * |
||
| 551 | * NOTE: Volatile api. May be moved to {@see LeftAndMain} |
||
| 552 | * |
||
| 553 | * @param File $file |
||
| 554 | * @return FormFactory |
||
| 555 | */ |
||
| 556 | public function getFormFactory(File $file) |
||
| 569 | |||
| 570 | /** |
||
| 571 | * The form is used to generate a form schema, |
||
| 572 | * as well as an intermediary object to process data through API endpoints. |
||
| 573 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
| 574 | * It handles both {@link File} and {@link Folder} records. |
||
| 575 | * |
||
| 576 | * @param int $id |
||
| 577 | * @return Form |
||
| 578 | */ |
||
| 579 | public function getFileEditForm($id) |
||
| 583 | |||
| 584 | /** |
||
| 585 | * Get file edit form |
||
| 586 | * |
||
| 587 | * @return Form |
||
| 588 | */ |
||
| 589 | View Code Duplication | public function fileEditForm() |
|
| 596 | |||
| 597 | /** |
||
| 598 | * The form is used to generate a form schema, |
||
| 599 | * as well as an intermediary object to process data through API endpoints. |
||
| 600 | * Since it's used directly on API endpoints, it does not have any form actions. |
||
| 601 | * It handles both {@link File} and {@link Folder} records. |
||
| 602 | * |
||
| 603 | * @param int $id |
||
| 604 | * @return Form |
||
| 605 | */ |
||
| 606 | public function getFileInsertForm($id) |
||
| 610 | |||
| 611 | /** |
||
| 612 | * Get file insert form |
||
| 613 | * |
||
| 614 | * @return Form |
||
| 615 | */ |
||
| 616 | View Code Duplication | public function fileInsertForm() |
|
| 623 | |||
| 624 | /** |
||
| 625 | * Abstract method for generating a form for a file |
||
| 626 | * |
||
| 627 | * @param int $id Record ID |
||
| 628 | * @param string $name Form name |
||
| 629 | * @param array $context Form context |
||
| 630 | * @return Form |
||
| 631 | */ |
||
| 632 | protected function getAbstractFileForm($id, $name, $context = []) |
||
| 661 | |||
| 662 | /** |
||
| 663 | * Get form for selecting a file |
||
| 664 | * |
||
| 665 | * @return Form |
||
| 666 | */ |
||
| 667 | public function fileSelectForm() |
||
| 674 | |||
| 675 | /** |
||
| 676 | * Get form for selecting a file |
||
| 677 | * |
||
| 678 | * @param int $id ID of the record being selected |
||
| 679 | * @return Form |
||
| 680 | */ |
||
| 681 | public function getFileSelectForm($id) |
||
| 685 | |||
| 686 | /** |
||
| 687 | * @param array $context |
||
| 688 | * @return Form |
||
| 689 | * @throws InvalidArgumentException |
||
| 690 | */ |
||
| 691 | public function getFileHistoryForm($context) |
||
| 733 | |||
| 734 | /** |
||
| 735 | * Gets a JSON schema representing the current edit form. |
||
| 736 | * |
||
| 737 | * WARNING: Experimental API. |
||
| 738 | * |
||
| 739 | * @param HTTPRequest $request |
||
| 740 | * @return HTTPResponse |
||
| 741 | */ |
||
| 742 | public function schema($request) |
||
| 765 | |||
| 766 | /** |
||
| 767 | * Get file history form |
||
| 768 | * |
||
| 769 | * @return Form |
||
| 770 | */ |
||
| 771 | public function fileHistoryForm() |
||
| 782 | |||
| 783 | /** |
||
| 784 | * @param array $data |
||
| 785 | * @param Form $form |
||
| 786 | * @return HTTPResponse |
||
| 787 | */ |
||
| 788 | public function save($data, $form) |
||
| 792 | |||
| 793 | /** |
||
| 794 | * @param array $data |
||
| 795 | * @param Form $form |
||
| 796 | * @return HTTPResponse |
||
| 797 | */ |
||
| 798 | public function publish($data, $form) |
||
| 802 | |||
| 803 | /** |
||
| 804 | * Update thisrecord |
||
| 805 | * |
||
| 806 | * @param array $data |
||
| 807 | * @param Form $form |
||
| 808 | * @param bool $doPublish |
||
| 809 | * @return HTTPResponse |
||
| 810 | */ |
||
| 811 | protected function saveOrPublish($data, $form, $doPublish = false) |
||
| 855 | |||
| 856 | public function unpublish($data, $form) |
||
| 880 | |||
| 881 | /** |
||
| 882 | * @param File $file |
||
| 883 | * |
||
| 884 | * @return array |
||
| 885 | */ |
||
| 886 | public function getObjectFromData(File $file) |
||
| 956 | |||
| 957 | /** |
||
| 958 | * Returns the files and subfolders contained in the currently selected folder, |
||
| 959 | * defaulting to the root node. Doubles as search results, if any search parameters |
||
| 960 | * are set through {@link SearchForm()}. |
||
| 961 | * |
||
| 962 | * @param array $params Unsanitised request parameters |
||
| 963 | * @return DataList |
||
| 964 | */ |
||
| 965 | protected function getList($params = array()) |
||
| 966 | { |
||
| 967 | $context = $this->getSearchContext(); |
||
| 968 | |||
| 969 | // Overwrite name filter to search both Name and Title attributes |
||
| 970 | $context->removeFilterByName('Name'); |
||
| 971 | |||
| 972 | // Lazy loaded list. Allows adding new filters through SearchContext. |
||
| 973 | /** @var DataList $list */ |
||
| 974 | $list = $context->getResults($params); |
||
| 975 | |||
| 976 | // Re-add previously removed "Name" filter as combined filter |
||
| 977 | // TODO Replace with composite SearchFilter once that API exists |
||
| 978 | if (!empty($params['Name'])) { |
||
| 979 | $list = $list->filterAny(array( |
||
| 980 | 'Name:PartialMatch' => $params['Name'], |
||
| 981 | 'Title:PartialMatch' => $params['Name'] |
||
| 982 | )); |
||
| 983 | } |
||
| 984 | |||
| 985 | // Optionally limit search to a folder (non-recursive) |
||
| 986 | if (!empty($params['ParentID']) && is_numeric($params['ParentID'])) { |
||
| 987 | $list = $list->filter('ParentID', $params['ParentID']); |
||
| 988 | } |
||
| 989 | |||
| 990 | // Date filtering |
||
| 991 | View Code Duplication | if (!empty($params['CreatedFrom'])) { |
|
| 992 | $fromDate = new DateField(null, null, $params['CreatedFrom']); |
||
| 993 | $list = $list->filter("Created:GreaterThanOrEqual", $fromDate->dataValue().' 00:00:00'); |
||
| 994 | } |
||
| 995 | View Code Duplication | if (!empty($params['CreatedTo'])) { |
|
| 996 | $toDate = new DateField(null, null, $params['CreatedTo']); |
||
| 997 | $list = $list->filter("Created:LessThanOrEqual", $toDate->dataValue().' 23:59:59'); |
||
| 998 | } |
||
| 999 | |||
| 1000 | // Categories |
||
| 1001 | if (!empty($filters['AppCategory']) && !empty(File::config()->app_categories[$filters['AppCategory']])) { |
||
| 1002 | $extensions = File::config()->app_categories[$filters['AppCategory']]; |
||
| 1003 | $list = $list->filter('Name:PartialMatch', $extensions); |
||
| 1004 | } |
||
| 1005 | |||
| 1006 | // Sort folders first |
||
| 1007 | $list = $list->sort( |
||
| 1008 | '(CASE WHEN "File"."ClassName" = \'Folder\' THEN 0 ELSE 1 END), "Name"' |
||
| 1009 | ); |
||
| 1010 | |||
| 1011 | // Pagination |
||
| 1012 | if (isset($filters['page']) && isset($filters['limit'])) { |
||
| 1013 | $page = $filters['page']; |
||
| 1014 | $limit = $filters['limit']; |
||
| 1015 | $offset = ($page - 1) * $limit; |
||
| 1016 | $list = $list->limit($limit, $offset); |
||
| 1017 | } |
||
| 1018 | |||
| 1019 | // Access checks |
||
| 1020 | $list = $list->filterByCallback(function (File $file) { |
||
| 1021 | return $file->canView(); |
||
| 1022 | }); |
||
| 1023 | |||
| 1024 | return $list; |
||
| 1025 | } |
||
| 1026 | |||
| 1027 | /** |
||
| 1028 | * Action handler for adding pages to a campaign |
||
| 1029 | * |
||
| 1030 | * @param array $data |
||
| 1031 | * @param Form $form |
||
| 1032 | * @return DBHTMLText|HTTPResponse |
||
| 1033 | */ |
||
| 1034 | public function addtocampaign($data, $form) |
||
| 1050 | |||
| 1051 | /** |
||
| 1052 | * Url handler for add to campaign form |
||
| 1053 | * |
||
| 1054 | * @param HTTPRequest $request |
||
| 1055 | * @return Form |
||
| 1056 | */ |
||
| 1057 | public function addToCampaignForm($request) |
||
| 1063 | |||
| 1064 | /** |
||
| 1065 | * @param int $id |
||
| 1066 | * @return Form |
||
| 1067 | */ |
||
| 1068 | public function getAddToCampaignForm($id) |
||
| 1102 | |||
| 1103 | /** |
||
| 1104 | * @return Upload |
||
| 1105 | */ |
||
| 1106 | protected function getUpload() |
||
| 1116 | |||
| 1117 | /** |
||
| 1118 | * Get response for successfully updated record |
||
| 1119 | * |
||
| 1120 | * @param File $record |
||
| 1121 | * @param Form $form |
||
| 1122 | * @return HTTPResponse |
||
| 1123 | */ |
||
| 1124 | protected function getRecordUpdatedResponse($record, $form) |
||
| 1131 | } |
||
| 1132 |