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