Completed
Pull Request — master (#1691)
by Damian
02:13
created

CMSPageAddController   C

Complexity

Total Complexity 19

Size/Duplication

Total Lines 194
Duplicated Lines 6.19 %

Coupling/Cohesion

Components 1
Dependencies 20

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 20
dl 12
loc 194
rs 6.4705
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B AddForm() 12 126 6
D doAdd() 0 40 12
A doCancel() 0 3 1

How to fix   Duplicated Code   

Duplicated Code

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:

1
<?php
2
3
namespace SilverStripe\CMS\Controllers;
4
5
use SilverStripe\CMS\Model\SiteTree;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Control\Session;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Forms\FieldList;
10
use SilverStripe\Forms\Form;
11
use SilverStripe\Forms\FormAction;
12
use SilverStripe\Forms\LiteralField;
13
use SilverStripe\Forms\OptionsetField;
14
use SilverStripe\Forms\SelectionGroup;
15
use SilverStripe\Forms\SelectionGroup_Item;
16
use SilverStripe\Forms\TreeDropdownField;
17
use SilverStripe\ORM\DataObject;
18
use SilverStripe\ORM\FieldType\DBField;
19
use SilverStripe\ORM\ValidationException;
20
use SilverStripe\ORM\ValidationResult;
21
use SilverStripe\Security\Member;
22
use SilverStripe\Security\Security;
23
24
class CMSPageAddController extends CMSPageEditController {
25
26
	private static $url_segment = 'pages/add';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
27
	private static $url_rule = '/$Action/$ID/$OtherID';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
28
	private static $url_priority = 42;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
29
	private static $menu_title = 'Add page';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
30
	private static $required_permission_codes = 'CMS_ACCESS_CMSMain';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
31
32
	private static $allowed_actions = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
33
		'AddForm',
34
		'doAdd',
35
		'doCancel'
36
	);
37
38
	/**
39
	 * @return Form
40
	 */
41
	public function AddForm() {
42
		$pageTypes = array();
43
		foreach($this->PageTypes() as $type) {
44
			$html = sprintf('<span class="page-icon class-%s"></span><span class="title">%s</span><span class="form__field-description">%s</span>',
45
				$type->getField('ClassName'),
46
				$type->getField('AddAction'),
47
				$type->getField('Description')
48
			);
49
			$pageTypes[$type->getField('ClassName')] = DBField::create_field('HTMLFragment', $html);
50
		}
51
		// Ensure generic page type shows on top
52
		if(isset($pageTypes['Page'])) {
53
			$pageTitle = $pageTypes['Page'];
54
			$pageTypes = array_merge(array('Page' => $pageTitle), $pageTypes);
55
		}
56
57
		$numericLabelTmpl = '<span class="step-label"><span class="flyout">Step %d. </span><span class="title">%s</span></span>';
58
59
		$topTitle = _t('CMSPageAddController.ParentMode_top', 'Top level');
60
		$childTitle = _t('CMSPageAddController.ParentMode_child', 'Under another page');
61
62
		$fields = new FieldList(
63
			$parentModeField = new SelectionGroup(
64
				"ParentModeField",
65
				array(
66
					new SelectionGroup_Item(
67
						"top",
68
						null,
69
						$topTitle
70
					),
71
					new SelectionGroup_Item(
72
						'child',
73
						$parentField = new TreeDropdownField(
74
							"ParentID",
75
							"",
76
							'SilverStripe\\CMS\\Model\\SiteTree',
77
							'ID',
78
							'TreeTitle'
79
						),
80
						$childTitle
81
					)
82
				)
83
			),
84
			new LiteralField(
85
				'RestrictedNote',
86
				sprintf(
87
					'<p class="message notice message-restricted">%s</p>',
88
					_t(
89
						'CMSMain.AddPageRestriction',
90
						'Note: Some page types are not allowed for this selection'
91
					)
92
				)
93
			),
94
			$typeField = new OptionsetField(
95
				"PageType",
96
				DBField::create_field(
97
					'HTMLFragment',
98
					sprintf($numericLabelTmpl, 2, _t('CMSMain.ChoosePageType', 'Choose page type'))
99
				),
100
				$pageTypes,
101
				'Page'
102
			)
103
		);
104
105
		$parentModeField->setTitle(DBField::create_field(
106
			'HTMLFragment',
107
			sprintf($numericLabelTmpl, 1, _t('CMSMain.ChoosePageParentMode', 'Choose where to create this page'))
108
		));
109
110
		$parentField->setSearchFunction(function ($sourceObject, $labelField, $search) {
111
			return DataObject::get($sourceObject)
112
				->filterAny([
113
					'MenuTitle:PartialMatch' => $search,
114
					'Title:PartialMatch' => $search,
115
				]);
116
		});
117
118
		// TODO Re-enable search once it allows for HTML title display,
119
		// see http://open.silverstripe.org/ticket/7455
120
		// $parentField->setShowSearch(true);
121
122
		$parentModeField->addExtraClass('parent-mode');
123
124
		// CMSMain->currentPageID() automatically sets the homepage,
125
		// which we need to counteract in the default selection (which should default to root, ID=0)
126
		if($parentID = $this->getRequest()->getVar('ParentID')) {
127
			$parentModeField->setValue('child');
128
			$parentField->setValue((int)$parentID);
129
		} else {
130
			$parentModeField->setValue('top');
131
		}
132
133
		$actions = new FieldList(
134
			FormAction::create("doAdd", _t('CMSMain.Create',"Create"))
135
				->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')
136
				->setUseButtonTag(true),
137
			FormAction::create("doCancel", _t('CMSMain.Cancel',"Cancel"))
138
				->addExtraClass('ss-ui-action-destructive ss-ui-action-cancel')
139
				->setUseButtonTag(true)
140
		);
141
142
		$this->extend('updatePageOptions', $fields);
143
144
		$negotiator = $this->getResponseNegotiator();
145
		$form = Form::create(
146
			$this, "AddForm", $fields, $actions
147
		)->setHTMLID('Form_AddForm');
148
		$form->setAttribute('data-hints', $this->SiteTreeHints());
149
		$form->setAttribute('data-childfilter', $this->Link('childfilter'));
150 View Code Duplication
		$form->setValidationResponseCallback(function(ValidationResult $errors) use ($negotiator, $form) {
0 ignored issues
show
Unused Code introduced by
The parameter $errors is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
			$request = $this->getRequest();
152
			if($request->isAjax() && $negotiator) {
153
				$result = $form->forTemplate();
154
				return $negotiator->respond($request, array(
155
					'CurrentForm' => function() use($result) {
156
						return $result;
157
					}
158
				));
159
			}
160
			return null;
161
		});
162
		$form->addExtraClass('flexbox-area-grow fill-height cms-add-form cms-content cms-edit-form ' . $this->BaseCSSClasses());
163
		$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
164
165
		return $form;
166
	}
167
168
	/**
169
	 * @param array $data
170
	 * @param Form $form
171
	 * @return HTTPResponse
172
	 */
173
	public function doAdd($data, $form) {
174
		$className = isset($data['PageType']) ? $data['PageType'] : "Page";
175
		$parentID = isset($data['ParentID']) ? (int)$data['ParentID'] : 0;
176
177
		$suffix = isset($data['Suffix']) ? "-" . $data['Suffix'] : null;
178
179
		if(!$parentID && isset($data['Parent'])) {
180
			$page = SiteTree::get_by_link($data['Parent']);
181
			if($page) $parentID = $page->ID;
182
		}
183
184
		if(is_numeric($parentID) && $parentID > 0) {
185
			$parentObj = SiteTree::get()->byID($parentID);
186
		} else {
187
			$parentObj = null;
188
		}
189
190
		if(!$parentObj || !$parentObj->ID) {
191
			$parentID = 0;
192
		}
193
194
		if(!singleton($className)->canCreate(Member::currentUser(), array('Parent' => $parentObj))) {
195
			return Security::permissionFailure($this);
196
		}
197
198
		$record = $this->getNewItem("new-$className-$parentID".$suffix, false);
199
		$this->extend('updateDoAdd', $record, $form);
200
		$record->write();
201
202
		$editController = CMSPageEditController::singleton();
203
		$editController->setCurrentPageID($record->ID);
204
205
		Session::set(
206
			"FormInfo.Form_EditForm.formError.message",
207
			_t('CMSMain.PageAdded', 'Successfully created page')
208
		);
209
		Session::set("FormInfo.Form_EditForm.formError.type", 'good');
210
211
		return $this->redirect(Controller::join_links($editController->Link('show'), $record->ID));
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->redirect(\SilverS...'show'), $record->ID)); of type string|null adds the type string to the return on line 211 which is incompatible with the return type documented by SilverStripe\CMS\Control...ageAddController::doAdd of type SilverStripe\Control\HTTPResponse|null.
Loading history...
212
	}
213
214
	public function doCancel($data, $form) {
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
215
		return $this->redirect(CMSMain::singleton()->Link());
216
	}
217
}
218