Completed
Push — master ( ba98f7...d2485a )
by Hamish
02:40
created

CMSPageAddController::AddForm()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 122
Code Lines 82

Duplication

Lines 13
Ratio 10.66 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
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
3
use SilverStripe\ORM\DataObject;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, DataObject.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
4
use SilverStripe\ORM\ValidationException;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, ValidationException.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
5
use SilverStripe\Security\Member;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Member.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use SilverStripe\Security\Security;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Security.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
8
class CMSPageAddController extends CMSPageEditController {
9
10
	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...
11
	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...
12
	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...
13
	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...
14
	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...
15
16
	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...
17
		'AddForm',
18
		'doAdd',
19
		'doCancel'
20
	);
21
22
	/**
23
	 * @return Form
24
	 */
25
	public function AddForm() {
26
		$pageTypes = array();
27
		foreach($this->PageTypes() as $type) {
28
			$html = sprintf('<span class="page-icon class-%s"></span><strong class="title">%s</strong><span class="description">%s</span>',
29
				$type->getField('ClassName'),
30
				$type->getField('AddAction'),
31
				$type->getField('Description')
32
			);
33
			$pageTypes[$type->getField('ClassName')] = $html;
34
		}
35
		// Ensure generic page type shows on top
36
		if(isset($pageTypes['Page'])) {
37
			$pageTitle = $pageTypes['Page'];
38
			$pageTypes = array_merge(array('Page' => $pageTitle), $pageTypes);
39
		}
40
41
		$numericLabelTmpl = '<div><label class="left"><span class="step-label"><span class="flyout">%d</span><span class="arrow"></span><span class="title">%s</span></span></label></div>';
42
43
		$topTitle = _t('CMSPageAddController.ParentMode_top', 'Top level');
44
		$childTitle = _t('CMSPageAddController.ParentMode_child', 'Under another page');
45
46
		$fields = new FieldList(
47
			new LiteralField('PageModeHeader', sprintf($numericLabelTmpl, 1, _t('CMSMain.ChoosePageParentMode', 'Choose where to create this page'))),
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
			$typeField = new OptionsetField(
70
				"PageType",
71
				sprintf($numericLabelTmpl, 2, _t('CMSMain.ChoosePageType', 'Choose page type')),
72
				$pageTypes,
73
				'Page'
74
			),
75
			new LiteralField(
76
				'RestrictedNote',
77
				sprintf(
78
					'<p class="message notice message-restricted">%s</p>',
79
					_t(
80
						'CMSMain.AddPageRestriction',
81
						'Note: Some page types are not allowed for this selection'
82
					)
83
				)
84
			)
85
		);
86
		$parentField->setSearchFunction(function ($sourceObject, $labelField, $search) {
87
			return DataObject::get(
88
				$sourceObject,
89
				sprintf(
90
					"\"MenuTitle\" LIKE '%%%s%%' OR \"Title\" LIKE '%%%s%%'",
91
					Convert::raw2sql($search),
92
					Convert::raw2sql($search)
93
				)
94
			);
95
		});
96
97
		// TODO Re-enable search once it allows for HTML title display,
98
		// see http://open.silverstripe.org/ticket/7455
99
		// $parentField->setShowSearch(true);
100
101
		$parentModeField->addExtraClass('parent-mode');
102
103
		// CMSMain->currentPageID() automatically sets the homepage,
104
		// which we need to counteract in the default selection (which should default to root, ID=0)
105
		if($parentID = $this->getRequest()->getVar('ParentID')) {
106
			$parentModeField->setValue('child');
107
			$parentField->setValue((int)$parentID);
108
		} else {
109
			$parentModeField->setValue('top');
110
		}
111
112
		$actions = new FieldList(
113
			FormAction::create("doAdd", _t('CMSMain.Create',"Create"))
114
				->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')
115
				->setUseButtonTag(true),
116
			FormAction::create("doCancel", _t('CMSMain.Cancel',"Cancel"))
117
				->addExtraClass('ss-ui-action-destructive ss-ui-action-cancel')
118
				->setUseButtonTag(true)
119
		);
120
121
		$this->extend('updatePageOptions', $fields);
122
123
		$negotiator = $this->getResponseNegotiator();
124
		$form = Form::create(
125
			$this, "AddForm", $fields, $actions
126
		)->setHTMLID('Form_AddForm');
127
		$form->setAttribute('data-hints', $this->SiteTreeHints());
128
		$form->setAttribute('data-childfilter', $this->Link('childfilter'));
129 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...
130
			$request = $this->getRequest();
131
			if($request->isAjax() && $negotiator) {
132
				$this->setupFormErrors();
133
				$result = $this->forTemplate();
134
135
				return $negotiator->respond($request, array(
136
					'CurrentForm' => function() use($result) {
137
						return $result;
138
					}
139
				));
140
			}
141
		});
142
		$form->addExtraClass('cms-add-form stacked cms-content center cms-edit-form ' . $this->BaseCSSClasses());
143
		$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
144
145
		return $form;
146
	}
147
148
	public function doAdd($data, $form) {
149
		$className = isset($data['PageType']) ? $data['PageType'] : "Page";
150
		$parentID = isset($data['ParentID']) ? (int)$data['ParentID'] : 0;
151
152
		$suffix = isset($data['Suffix']) ? "-" . $data['Suffix'] : null;
153
154
		if(!$parentID && isset($data['Parent'])) {
155
			$page = SiteTree::get_by_link($data['Parent']);
156
			if($page) $parentID = $page->ID;
157
		}
158
159
		if(is_numeric($parentID) && $parentID > 0) $parentObj = DataObject::get_by_id("SiteTree", $parentID);
160
		else $parentObj = null;
161
162
		if(!$parentObj || !$parentObj->ID) $parentID = 0;
163
164
		if(!singleton($className)->canCreate(Member::currentUser(), array('Parent' => $parentObj))) {
165
			return Security::permissionFailure($this);
166
		}
167
168
		$record = $this->getNewItem("new-$className-$parentID".$suffix, false);
169
		$this->extend('updateDoAdd', $record, $form);
170
171
		try {
172
			$record->write();
173
		} catch(ValidationException $ex) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\ORM\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...
174
			$form->sessionMessage($ex->getResult()->message(), 'bad');
175
			return $this->getResponseNegotiator()->respond($this->getRequest());
176
		}
177
178
		$editController = singleton('CMSPageEditController');
179
		$editController->setCurrentPageID($record->ID);
180
181
		Session::set(
182
			"FormInfo.Form_EditForm.formError.message",
183
			_t('CMSMain.PageAdded', 'Successfully created page')
184
		);
185
		Session::set("FormInfo.Form_EditForm.formError.type", 'good');
186
187
		return $this->redirect(Controller::join_links(singleton('CMSPageEditController')->Link('show'), $record->ID));
188
	}
189
190
	public function doCancel($data, $form) {
191
		return $this->redirect(singleton('CMSMain')->Link());
192
	}
193
194
}
195