Completed
Pull Request — master (#1568)
by
unknown
02:39
created

CMSPageAddController::doCancel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
use SilverStripe\ORM\DataObject;
4
use SilverStripe\ORM\FieldType\DBField;
5
use SilverStripe\ORM\ValidationException;
6
use SilverStripe\Security\Member;
7
use SilverStripe\Security\Security;
8
9
class CMSPageAddController extends CMSPageEditController {
10
11
	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...
12
	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...
13
	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...
14
	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...
15
	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...
16
17
	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...
18
		'AddForm',
19
		'doAdd',
20
		'doCancel'
21
	);
22
23
	/**
24
	 * @return Form
25
	 */
26
	public function AddForm() {
27
		$pageTypes = array();
28
		foreach($this->PageTypes() as $type) {
29
			$html = sprintf('<span class="page-icon class-%s"></span><span class="title">%s</span><span class="form__field-description">%s</span>',
30
				$type->getField('ClassName'),
31
				$type->getField('AddAction'),
32
				$type->getField('Description')
33
			);
34
			$pageTypes[$type->getField('ClassName')] = DBField::create_field('HTMLFragment', $html);
35
		}
36
		// Ensure generic page type shows on top
37
		if(isset($pageTypes['Page'])) {
38
			$pageTitle = $pageTypes['Page'];
39
			$pageTypes = array_merge(array('Page' => $pageTitle), $pageTypes);
40
		}
41
42
		$numericLabelTmpl = '<span class="step-label"><span class="flyout">Step %d. </span><span class="title">%s</span></span>';
43
44
		$topTitle = _t('CMSPageAddController.ParentMode_top', 'Top level');
45
		$childTitle = _t('CMSPageAddController.ParentMode_child', 'Under another page');
46
47
		$fields = new FieldList(
48
			$parentModeField = new SelectionGroup(
49
				"ParentModeField",
50
				array(
51
					new SelectionGroup_Item(
52
						"top",
53
						null,
54
						$topTitle
55
					),
56
					new SelectionGroup_Item(
57
						'child',
58
						$parentField = new TreeDropdownField(
59
							"ParentID",
60
							"",
61
							'SiteTree',
62
							'ID',
63
							'TreeTitle'
64
						),
65
						$childTitle
66
					)
67
				)
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
			$typeField = new OptionsetField(
80
				"PageType",
81
				DBField::create_field(
82
					'HTMLFragment',
83
					sprintf($numericLabelTmpl, 2, _t('CMSMain.ChoosePageType', 'Choose page type'))
84
				),
85
				$pageTypes,
86
				'Page'
87
			)
88
		);
89
90
		$parentModeField->setTitle(DBField::create_field(
91
			'HTMLFragment',
92
			sprintf($numericLabelTmpl, 1, _t('CMSMain.ChoosePageParentMode', 'Choose where to create this page'))
93
		));
94
95
		$parentField->setSearchFunction(function ($sourceObject, $labelField, $search) {
96
			return DataObject::get($sourceObject)
97
				->filterAny([
98
					'MenuTitle:PartialMatch' => $search,
99
					'Title:PartialMatch' => $search,
100
				]);
101
		});
102
103
		// TODO Re-enable search once it allows for HTML title display,
104
		// see http://open.silverstripe.org/ticket/7455
105
		// $parentField->setShowSearch(true);
106
107
		$parentModeField->addExtraClass('parent-mode');
108
109
		// CMSMain->currentPageID() automatically sets the homepage,
110
		// which we need to counteract in the default selection (which should default to root, ID=0)
111
		if($parentID = $this->getRequest()->getVar('ParentID')) {
112
			$parentModeField->setValue('child');
113
			$parentField->setValue((int)$parentID);
114
		} else {
115
			$parentModeField->setValue('top');
116
		}
117
118
		$actions = new FieldList(
119
			FormAction::create("doAdd", _t('CMSMain.Create',"Create"))
120
				->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')
121
				->setUseButtonTag(true),
122
			FormAction::create("doCancel", _t('CMSMain.Cancel',"Cancel"))
123
				->addExtraClass('ss-ui-action-destructive ss-ui-action-cancel')
124
				->setUseButtonTag(true)
125
		);
126
127
		$this->extend('updatePageOptions', $fields);
128
129
		$negotiator = $this->getResponseNegotiator();
130
		$form = Form::create(
131
			$this, "AddForm", $fields, $actions
132
		)->setHTMLID('Form_AddForm');
133
		$form->setAttribute('data-hints', $this->SiteTreeHints());
134
		$form->setAttribute('data-childfilter', $this->Link('childfilter'));
135 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...
136
			$request = $this->getRequest();
137
			if($request->isAjax() && $negotiator) {
138
				$this->setupFormErrors();
0 ignored issues
show
Documentation Bug introduced by
The method setupFormErrors does not exist on object<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...
139
				$result = $this->forTemplate();
0 ignored issues
show
Documentation Bug introduced by
The method forTemplate does not exist on object<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...
140
141
				return $negotiator->respond($request, array(
142
					'CurrentForm' => function() use($result) {
143
						return $result;
144
					}
145
				));
146
			}
147
		});
148
		$form->addExtraClass('cms-add-form cms-content center cms-edit-form ' . $this->BaseCSSClasses());
149
		$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...
150
151
		return $form;
152
	}
153
154
	public function doAdd($data, $form) {
155
		$className = isset($data['PageType']) ? $data['PageType'] : "Page";
156
		$parentID = isset($data['ParentID']) ? (int)$data['ParentID'] : 0;
157
158
		$suffix = isset($data['Suffix']) ? "-" . $data['Suffix'] : null;
159
160
		if(!$parentID && isset($data['Parent'])) {
161
			$page = SiteTree::get_by_link($data['Parent']);
162
			if($page) $parentID = $page->ID;
163
		}
164
165
		if(is_numeric($parentID) && $parentID > 0) $parentObj = DataObject::get_by_id("SiteTree", $parentID);
166
		else $parentObj = null;
167
168
		if(!$parentObj || !$parentObj->ID) $parentID = 0;
169
170
		if(!singleton($className)->canCreate(Member::currentUser(), array('Parent' => $parentObj))) {
171
			return Security::permissionFailure($this);
172
		}
173
174
		$record = $this->getNewItem("new-$className-$parentID".$suffix, false);
175
		$this->extend('updateDoAdd', $record, $form);
176
177
		try {
178
			$record->write();
179
		} catch(ValidationException $ex) {
180
			$form->sessionMessage($ex->getResult()->message(), 'bad');
181
			return $this->getResponseNegotiator()->respond($this->getRequest());
182
		}
183
184
		$editController = singleton('CMSPageEditController');
185
		$editController->setCurrentPageID($record->ID);
186
187
		Session::set(
188
			"FormInfo.Form_EditForm.formError.message",
189
			_t('CMSMain.PageAdded', 'Successfully created page')
190
		);
191
		Session::set("FormInfo.Form_EditForm.formError.type", 'good');
192
193
		return $this->redirect(Controller::join_links(singleton('CMSPageEditController')->Link('show'), $record->ID));
194
	}
195
196
	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...
197
		return $this->redirect(singleton('CMSMain')->Link());
198
	}
199
200
}
201