Completed
Push — master ( 25a8fb...29fc7a )
by Hamish
12s
created

CMSPageAddController::doAdd()   F

Complexity

Conditions 13
Paths 288

Size

Total Lines 46
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 46
rs 3.7737
c 2
b 0
f 0
cc 13
eloc 29
nc 288
nop 2

How to fix   Complexity   

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

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
155
				$result = $this->forTemplate();
0 ignored issues
show
Documentation Bug introduced by
The method forTemplate does not exist on object<SilverStripe\CMS\...s\CMSPageAddController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
156
157
				return $negotiator->respond($request, array(
158
					'CurrentForm' => function() use($result) {
159
						return $result;
160
					}
161
				));
162
			}
163
		});
164
		$form->addExtraClass('cms-add-form cms-content center cms-edit-form ' . $this->BaseCSSClasses());
165
		$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
0 ignored issues
show
Documentation introduced by
$this->getTemplatesWithSuffix('_EditForm') is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
166
167
		return $form;
168
	}
169
170
	public function doAdd($data, $form) {
171
		$className = isset($data['PageType']) ? $data['PageType'] : "Page";
172
		$parentID = isset($data['ParentID']) ? (int)$data['ParentID'] : 0;
173
174
		$suffix = isset($data['Suffix']) ? "-" . $data['Suffix'] : null;
175
176
		if(!$parentID && isset($data['Parent'])) {
177
			$page = SiteTree::get_by_link($data['Parent']);
178
			if($page) $parentID = $page->ID;
179
		}
180
181
		if(is_numeric($parentID) && $parentID > 0) {
182
			$parentObj = SiteTree::get()->byID($parentID);
183
		} else {
184
			$parentObj = null;
185
		}
186
187
		if(!$parentObj || !$parentObj->ID) {
188
			$parentID = 0;
189
		}
190
191
		if(!singleton($className)->canCreate(Member::currentUser(), array('Parent' => $parentObj))) {
192
			return Security::permissionFailure($this);
193
		}
194
195
		$record = $this->getNewItem("new-$className-$parentID".$suffix, false);
196
		$this->extend('updateDoAdd', $record, $form);
197
198
		try {
199
			$record->write();
200
		} catch(ValidationException $ex) {
201
			$form->sessionMessage($ex->getResult()->message(), 'bad');
202
			return $this->getResponseNegotiator()->respond($this->getRequest());
203
		}
204
205
		$editController = CMSPageEditController::singleton();
206
		$editController->setCurrentPageID($record->ID);
207
208
		Session::set(
209
			"FormInfo.Form_EditForm.formError.message",
210
			_t('CMSMain.PageAdded', 'Successfully created page')
211
		);
212
		Session::set("FormInfo.Form_EditForm.formError.type", 'good');
213
214
		return $this->redirect(Controller::join_links($editController->Link('show'), $record->ID));
215
	}
216
217
	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...
218
		return $this->redirect(CMSMain::singleton()->Link());
219
	}
220
}
221