Completed
Pull Request — master (#1458)
by Sam
04:45 queued 02:13
created

CMSPageAddController::AddForm()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 122
Code Lines 82

Duplication

Lines 13
Ratio 10.66 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 13
loc 122
rs 8.1463
cc 6
eloc 82
nc 8
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
class CMSPageAddController extends CMSPageEditController {
0 ignored issues
show
Bug introduced by
There is one abstract method isCurrentPage in this class; you could implement it, or declare this class as abstract.
Loading history...
3
4
	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...
5
	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...
6
	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...
7
	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...
8
	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...
9
10
	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...
11
		'AddForm',
12
		'doAdd',
13
		'doCancel'
14
	);
15
16
	/**
17
	 * @return Form
18
	 */
19
	public function AddForm() {
20
		$pageTypes = array();
21
		foreach($this->PageTypes() as $type) {
22
			$html = sprintf('<span class="page-icon class-%s"></span><strong class="title">%s</strong><span class="description">%s</span>',
23
				$type->getField('ClassName'),
24
				$type->getField('AddAction'),
25
				$type->getField('Description')
26
			);
27
			$pageTypes[$type->getField('ClassName')] = $html;
28
		}
29
		// Ensure generic page type shows on top
30
		if(isset($pageTypes['Page'])) {
31
			$pageTitle = $pageTypes['Page'];
32
			$pageTypes = array_merge(array('Page' => $pageTitle), $pageTypes);
33
		}
34
35
		$numericLabelTmpl = '<span class="step-label"><span class="flyout">%d</span><span class="arrow"></span><span class="title">%s</span></span>';
36
37
		$topTitle = _t('CMSPageAddController.ParentMode_top', 'Top level');
38
		$childTitle = _t('CMSPageAddController.ParentMode_child', 'Under another page');
39
40
		$fields = new FieldList(
41
			new LiteralField('PageModeHeader', sprintf($numericLabelTmpl, 1, _t('CMSMain.ChoosePageParentMode', 'Choose where to create this page'))),
42
			$parentModeField = new SelectionGroup(
43
				"ParentModeField",
44
				array(
45
					new SelectionGroup_Item(
46
						"top",
47
						null,
48
						$topTitle
49
					),
50
					new SelectionGroup_Item(
51
						'child',
52
						$parentField = new TreeDropdownField(
53
							"ParentID",
54
							"",
55
							'SiteTree',
56
							'ID',
57
							'TreeTitle'
58
						),
59
						$childTitle
60
					)
61
				)
62
			),
63
			$typeField = new OptionsetField(
64
				"PageType",
65
				sprintf($numericLabelTmpl, 2, _t('CMSMain.ChoosePageType', 'Choose page type')),
66
				$pageTypes,
67
				'Page'
68
			),
69
			new LiteralField(
70
				'RestrictedNote',
71
				sprintf(
72
					'<p class="message notice message-restricted">%s</p>',
73
					_t(
74
						'CMSMain.AddPageRestriction',
75
						'Note: Some page types are not allowed for this selection'
76
					)
77
				)
78
			)
79
		);
80
		$parentField->setSearchFunction(function ($sourceObject, $labelField, $search) {
81
			return DataObject::get(
82
				$sourceObject,
83
				sprintf(
84
					"\"MenuTitle\" LIKE '%%%s%%' OR \"Title\" LIKE '%%%s%%'",
85
					Convert::raw2sql($search),
86
					Convert::raw2sql($search)
87
				)
88
			);
89
		});
90
91
		// TODO Re-enable search once it allows for HTML title display,
92
		// see http://open.silverstripe.org/ticket/7455
93
		// $parentField->setShowSearch(true);
94
95
		$parentModeField->addExtraClass('parent-mode');
96
97
		// CMSMain->currentPageID() automatically sets the homepage,
98
		// which we need to counteract in the default selection (which should default to root, ID=0)
99
		if($parentID = $this->getRequest()->getVar('ParentID')) {
100
			$parentModeField->setValue('child');
101
			$parentField->setValue((int)$parentID);
102
		} else {
103
			$parentModeField->setValue('top');
104
		}
105
106
		$actions = new FieldList(
107
			FormAction::create("doAdd", _t('CMSMain.Create',"Create"))
108
				->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')
109
				->setUseButtonTag(true),
110
			FormAction::create("doCancel", _t('CMSMain.Cancel',"Cancel"))
111
				->addExtraClass('ss-ui-action-destructive ss-ui-action-cancel')
112
				->setUseButtonTag(true)
113
		);
114
115
		$this->extend('updatePageOptions', $fields);
116
117
		$negotiator = $this->getResponseNegotiator();
118
		$form = Form::create(
119
			$this, "AddForm", $fields, $actions
120
		)->setHTMLID('Form_AddForm');
121
		$form->setAttribute('data-hints', $this->SiteTreeHints());
122
		$form->setAttribute('data-childfilter', $this->Link('childfilter'));
123 View Code Duplication
		$form->setValidationResponseCallback(function() use ($negotiator, $form) {
0 ignored issues
show
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...
124
			$request = $this->getRequest();
125
			if($request->isAjax() && $negotiator) {
126
				$this->setupFormErrors();
127
				$result = $this->forTemplate();
128
129
				return $negotiator->respond($request, array(
130
					'CurrentForm' => function() use($result) {
131
						return $result;
132
					}
133
				));
134
			}
135
		});
136
		$form->addExtraClass('cms-add-form stacked cms-content center cms-edit-form ' . $this->BaseCSSClasses());
137
		$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
138
139
		return $form;
140
	}
141
142
	public function doAdd($data, $form) {
143
		$className = isset($data['PageType']) ? $data['PageType'] : "Page";
144
		$parentID = isset($data['ParentID']) ? (int)$data['ParentID'] : 0;
145
146
		$suffix = isset($data['Suffix']) ? "-" . $data['Suffix'] : null;
147
148
		if(!$parentID && isset($data['Parent'])) {
149
			$page = SiteTree::get_by_link($data['Parent']);
150
			if($page) $parentID = $page->ID;
151
		}
152
153
		if(is_numeric($parentID) && $parentID > 0) $parentObj = DataObject::get_by_id("SiteTree", $parentID);
154
		else $parentObj = null;
155
156
		if(!$parentObj || !$parentObj->ID) $parentID = 0;
157
158
		if(!singleton($className)->canCreate(Member::currentUser(), array('Parent' => $parentObj))) {
159
			return Security::permissionFailure($this);
160
		}
161
162
		$record = $this->getNewItem("new-$className-$parentID".$suffix, false);
163
		if(class_exists('Translatable') && $record->hasExtension('Translatable') && isset($data['Locale'])) {
164
			$record->Locale = $data['Locale'];
165
		}
166
167
		try {
168
			$record->write();
169
		} catch(ValidationException $ex) {
0 ignored issues
show
Bug introduced by
The class ValidationException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
170
			$form->sessionMessage($ex->getResult()->message(), 'bad');
171
			return $this->getResponseNegotiator()->respond($this->getRequest());
172
		}
173
174
		$editController = singleton('CMSPageEditController');
175
		$editController->setCurrentPageID($record->ID);
176
177
		Session::set(
178
			"FormInfo.Form_EditForm.formError.message",
179
			_t('CMSMain.PageAdded', 'Successfully created page')
180
		);
181
		Session::set("FormInfo.Form_EditForm.formError.type", 'good');
182
183
		return $this->redirect(Controller::join_links(singleton('CMSPageEditController')->Link('show'), $record->ID));
184
	}
185
186
	public function doCancel($data, $form) {
187
		return $this->redirect(singleton('CMSMain')->Link());
188
	}
189
190
}
191