Completed
Push — master ( 431714...89deba )
by Daniel
10s
created

CMSPageHistoryController   D

Complexity

Total Complexity 48

Size/Duplication

Total Lines 434
Duplicated Lines 10.83 %

Coupling/Cohesion

Components 1
Dependencies 19

Importance

Changes 0
Metric Value
wmc 48
lcom 1
cbo 19
dl 47
loc 434
rs 4.8854
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getResponseNegotiator() 0 13 2
A show() 14 14 2
A compare() 17 17 2
A getSilverStripeNavigator() 0 9 2
C getEditForm() 0 76 9
C VersionsForm() 0 84 9
B doCompare() 8 28 3
B doShowVersion() 8 27 5
A ShowVersionForm() 0 8 2
C CompareVersionsForm() 0 62 11
A Breadcrumbs() 0 5 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like CMSPageHistoryController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CMSPageHistoryController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace SilverStripe\CMS\Controllers;
4
5
use SilverStripe\CMS\Model\SiteTree;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Control\HTTPRequest;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Forms\CheckboxField;
10
use SilverStripe\Forms\FieldList;
11
use SilverStripe\Forms\Form;
12
use SilverStripe\Forms\FormAction;
13
use SilverStripe\Forms\HiddenField;
14
use SilverStripe\Forms\LiteralField;
15
use SilverStripe\ORM\FieldType\DBField;
16
use SilverStripe\ORM\FieldType\DBHTMLText;
17
use SilverStripe\ORM\Versioning\Versioned;
18
use SilverStripe\Security\Security;
19
use SilverStripe\View\ArrayData;
20
use SilverStripe\View\ViewableData;
21
22
class CMSPageHistoryController extends CMSMain {
23
24
	private static $url_segment = 'pages/history';
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...
25
26
	private static $url_rule = '/$Action/$ID/$VersionID/$OtherVersionID';
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...
27
28
	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...
29
30
	private static $menu_title = 'History';
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
32
	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...
33
34
	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...
35
		'VersionsForm',
36
		'CompareVersionsForm',
37
		'show',
38
		'compare'
39
	);
40
41
	private static $url_handlers = 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...
42
		'$Action/$ID/$VersionID/$OtherVersionID' => 'handleAction'
43
	);
44
45
	public function getResponseNegotiator() {
46
		$negotiator = parent::getResponseNegotiator();
47
		$controller = $this;
48
		$negotiator->setCallback('CurrentForm', function() use(&$controller) {
49
			$form = $controller->ShowVersionForm($controller->getRequest()->param('VersionID'));
50
			if($form) return $form->forTemplate();
51
			else return $controller->renderWith($controller->getTemplatesWithSuffix('_Content'));
52
		});
53
		$negotiator->setCallback('default', function() use(&$controller) {
54
			return $controller->renderWith($controller->getViewer('show'));
55
		});
56
		return $negotiator;
57
	}
58
59
	/**
60
	 * @param HTTPRequest $request
61
	 * @return array
62
	 */
63 View Code Duplication
	public function show($request) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
64
		$form = $this->ShowVersionForm($request->param('VersionID'));
65
66
		$negotiator = $this->getResponseNegotiator();
67
		$controller = $this;
68
		$negotiator->setCallback('CurrentForm', function() use(&$controller, &$form) {
69
			return $form ? $form->forTemplate() : $controller->renderWith($controller->getTemplatesWithSuffix('_Content'));
70
		});
71
		$negotiator->setCallback('default', function() use(&$controller, &$form) {
72
			return $controller->customise(array('EditForm' => $form))->renderWith($controller->getViewer('show'));
73
		});
74
75
		return $negotiator->respond($request);
76
	}
77
78
	/**
79
	 * @param HTTPRequest $request
80
	 * @return array
81
	 */
82 View Code Duplication
	public function compare($request) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
83
		$form = $this->CompareVersionsForm(
84
			$request->param('VersionID'),
85
			$request->param('OtherVersionID')
86
		);
87
88
		$negotiator = $this->getResponseNegotiator();
89
		$controller = $this;
90
		$negotiator->setCallback('CurrentForm', function() use(&$controller, &$form) {
91
			return $form ? $form->forTemplate() : $controller->renderWith($controller->getTemplatesWithSuffix('_Content'));
92
		});
93
		$negotiator->setCallback('default', function() use(&$controller, &$form) {
94
			return $controller->customise(array('EditForm' => $form))->renderWith($controller->getViewer('show'));
95
		});
96
97
		return $negotiator->respond($request);
98
	}
99
100
	public function getSilverStripeNavigator() {
101
		$record = $this->getRecord($this->currentPageID(), $this->getRequest()->param('VersionID'));
102
		if($record) {
103
			$navigator = new SilverStripeNavigator($record);
104
			return $navigator->renderWith($this->getTemplatesWithSuffix('_SilverStripeNavigator'));
105
		} else {
106
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type of the parent method SilverStripe\Admin\LeftA...etSilverStripeNavigator of type SilverStripe\ORM\FieldType\DBHTMLText.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
107
		}
108
	}
109
110
	/**
111
	 * Returns the read only version of the edit form. Detaches all {@link FormAction}
112
	 * instances attached since only action relates to revert.
113
	 *
114
	 * Permission checking is done at the {@link CMSMain::getEditForm()} level.
115
	 *
116
	 * @param int $id ID of the record to show
117
	 * @param array $fields optional
118
	 * @param int $versionID
119
	 * @param int $compareID Compare mode
120
	 *
121
	 * @return Form
122
	 */
123
	public function getEditForm($id = null, $fields = null, $versionID = null, $compareID = null) {
124
		if(!$id) $id = $this->currentPageID();
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
125
126
		$record = $this->getRecord($id, $versionID);
127
		$versionID = ($record) ? $record->Version : $versionID;
0 ignored issues
show
Bug introduced by
The property Version does not seem to exist. Did you mean versioning?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
128
129
		$form = parent::getEditForm($record, ($record) ? $record->getCMSFields() : null);
0 ignored issues
show
Documentation introduced by
$record is of type object<SilverStripe\CMS\Model\SiteTree>, but the function expects a integer|null.

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...
130
		// Respect permission failures from parent implementation
131
		if(!($form instanceof Form)) return $form;
132
133
		// TODO: move to the SilverStripeNavigator structure so the new preview can pick it up.
134
		//$nav = new SilverStripeNavigatorItem_ArchiveLink($record);
135
136
		$form->setActions(new FieldList(
137
			$revert = FormAction::create('doRollback', _t('CMSPageHistoryController.REVERTTOTHISVERSION', 'Revert to this version'))->setUseButtonTag(true)
138
		));
139
140
		$fields = $form->Fields();
141
		$fields->removeByName("Status");
142
		$fields->push(new HiddenField("ID"));
143
		$fields->push(new HiddenField("Version"));
144
145
		$fields = $fields->makeReadonly();
146
147
		if($compareID) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $compareID of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
148
			$link = Controller::join_links(
149
				$this->Link('show'),
150
				$id
151
			);
152
153
			$view = _t('CMSPageHistoryController.VIEW',"view");
154
155
			$message = _t(
156
				'CMSPageHistoryController.COMPARINGVERSION',
157
				"Comparing versions {version1} and {version2}.",
158
				array(
0 ignored issues
show
Documentation introduced by
array('version1' => spri...k, $compareID), $view)) is of type array<string,string,{"ve...","version2":"string"}>, 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...
159
					'version1' => sprintf('%s (<a href="%s">%s</a>)', $versionID, Controller::join_links($link, $versionID), $view),
160
					'version2' => sprintf('%s (<a href="%s">%s</a>)', $compareID, Controller::join_links($link, $compareID), $view)
161
				)
162
			);
163
164
			$revert->setReadonly(true);
165
		} else {
166
			if($record->isLatestVersion()) {
0 ignored issues
show
Documentation Bug introduced by
The method isLatestVersion does not exist on object<SilverStripe\CMS\Model\SiteTree>? 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...
167
				$message = _t('CMSPageHistoryController.VIEWINGLATEST', 'Currently viewing the latest version.');
168
			} else {
169
				$message = _t(
170
					'CMSPageHistoryController.VIEWINGVERSION',
171
					"Currently viewing version {version}.",
172
					array('version' => $versionID)
0 ignored issues
show
Documentation introduced by
array('version' => $versionID) is of type array<string,?,{"version":"?"}>, 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...
173
				);
174
			}
175
		}
176
177
		$fields->addFieldToTab('Root.Main',
178
			new LiteralField('CurrentlyViewingMessage', ArrayData::create(array(
179
				'Content' => DBField::create_field('HTMLFragment', $message),
180
				'Classes' => 'notice'
181
			))->renderWith($this->getTemplatesWithSuffix('_notice'))),
182
			"Title"
183
		);
184
185
		$form->setFields($fields->makeReadonly());
186
		$form->loadDataFrom(array(
187
			"ID" => $id,
188
			"Version" => $versionID,
189
		));
190
191
		if(($record && $record->isLatestVersion())) {
0 ignored issues
show
Documentation Bug introduced by
The method isLatestVersion does not exist on object<SilverStripe\CMS\Model\SiteTree>? 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...
192
			$revert->setReadonly(true);
193
		}
194
195
		$form->removeExtraClass('cms-content');
196
197
		return $form;
198
	}
199
200
201
	/**
202
	 * Version select form. Main interface between selecting versions to view
203
	 * and comparing multiple versions.
204
	 *
205
	 * Because we can reload the page directly to a compare view (history/compare/1/2/3)
206
	 * this form has to adapt to those parameters as well.
207
	 *
208
	 * @return Form
209
	 */
210
	public function VersionsForm() {
211
		$id = $this->currentPageID();
212
		$page = $this->getRecord($id);
213
		$versionsHtml = '';
214
215
		$action = $this->getRequest()->param('Action');
216
		$versionID = $this->getRequest()->param('VersionID');
217
		$otherVersionID = $this->getRequest()->param('OtherVersionID');
218
219
		$showUnpublishedChecked = 0;
220
		$compareModeChecked = ($action == "compare");
221
222
		if($page) {
223
			$versions = $page->allVersions();
0 ignored issues
show
Documentation Bug introduced by
The method allVersions does not exist on object<SilverStripe\CMS\Model\SiteTree>? 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...
224
			$versionID = (!$versionID) ? $page->Version : $versionID;
0 ignored issues
show
Bug introduced by
The property Version does not seem to exist. Did you mean versioning?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
225
226
			if($versions) {
227
				foreach($versions as $k => $version) {
228
					$active = false;
229
230
					if($version->Version == $versionID || $version->Version == $otherVersionID) {
231
						$active = true;
232
233
						if(!$version->WasPublished) $showUnpublishedChecked = 1;
234
					}
235
236
					$version->Active = ($active);
237
				}
238
			}
239
240
			$vd = new ViewableData();
241
242
			$versionsHtml = $vd->customise(array(
243
				'Versions' => $versions
244
			))->renderWith($this->getTemplatesWithSuffix('_versions'));
245
		}
246
247
		$fields = new FieldList(
248
			new CheckboxField(
249
				'ShowUnpublished',
250
				_t('CMSPageHistoryController.SHOWUNPUBLISHED','Show unpublished versions'),
251
				$showUnpublishedChecked
252
			),
253
			new CheckboxField(
254
				'CompareMode',
255
				_t('CMSPageHistoryController.COMPAREMODE', 'Compare mode (select two)'),
256
				$compareModeChecked
257
			),
258
			new LiteralField('VersionsHtml', $versionsHtml),
0 ignored issues
show
Bug introduced by
It seems like $versionsHtml defined by $vd->customise(array('Ve...ithSuffix('_versions')) on line 242 can also be of type object<SilverStripe\ORM\FieldType\DBHTMLText>; however, SilverStripe\Forms\LiteralField::__construct() does only seem to accept string|object<SilverStripe\Forms\FormField>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
259
			$hiddenID = new HiddenField('ID', false, "")
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a null|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...
260
		);
261
262
		$actions = new FieldList(
263
			new FormAction(
264
				'doCompare', _t('CMSPageHistoryController.COMPAREVERSIONS','Compare Versions')
265
			),
266
			new FormAction(
267
				'doShowVersion', _t('CMSPageHistoryController.SHOWVERSION','Show Version')
268
			)
269
		);
270
271
		// Use <button> to allow full jQuery UI styling
272
		foreach($actions->dataFields() as $action) {
273
			/** @var FormAction $action */
274
			$action->setUseButtonTag(true);
275
		}
276
277
		$form = Form::create(
278
			$this,
279
			'VersionsForm',
280
			$fields,
281
			$actions
282
		)->setHTMLID('Form_VersionsForm');
283
		$form->loadDataFrom($this->getRequest()->requestVars());
284
		$hiddenID->setValue($id);
285
		$form->unsetValidator();
286
287
		$form
288
			->addExtraClass('cms-versions-form') // placeholder, necessary for $.metadata() to work
289
			->setAttribute('data-link-tmpl-compare', Controller::join_links($this->Link('compare'), '%s', '%s', '%s'))
290
			->setAttribute('data-link-tmpl-show', Controller::join_links($this->Link('show'), '%s', '%s'));
291
292
		return $form;
293
	}
294
295
	/**
296
	 * Process the {@link VersionsForm} compare function between two pages.
297
	 *
298
	 * @param array $data
299
	 * @param Form $form
300
	 * @return HTTPResponse|DBHTMLText
301
	 */
302
	public function doCompare($data, $form) {
0 ignored issues
show
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...
303
		$versions = $data['Versions'];
304
		if(count($versions) < 2) {
305
			return null;
306
		}
307
308
		$version1 = array_shift($versions);
309
		$version2 = array_shift($versions);
310
311
		$form = $this->CompareVersionsForm($version1, $version2);
312
313
		// javascript solution, render into template
314 View Code Duplication
		if($this->getRequest()->isAjax()) {
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...
315
			return $this->customise(array(
316
				"EditForm" => $form
317
			))->renderWith(array(
318
				static::class . '_EditForm',
319
				'LeftAndMain_Content'
320
			));
321
		}
322
323
		// non javascript, redirect the user to the page
324
		return $this->redirect(Controller::join_links(
325
			$this->Link('compare'),
326
			$version1,
327
			$version2
328
		));
329
	}
330
331
	/**
332
	 * Process the {@link VersionsForm} show version function. Only requires
333
	 * one page to be selected.
334
	 *
335
	 * @param array
336
	 * @param Form
337
	 *
338
	 * @return DBHTMLText|HTTPResponse
339
	 */
340
	public function doShowVersion($data, $form) {
0 ignored issues
show
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...
341
		$versionID = null;
342
343
		if(isset($data['Versions']) && is_array($data['Versions'])) {
344
			$versionID  = array_shift($data['Versions']);
345
		}
346
347
		if(!$versionID) {
348
			return null;
349
		}
350
351
		$request = $this->getRequest();
352 View Code Duplication
		if($request->isAjax()) {
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...
353
			return $this->customise(array(
354
				"EditForm" => $this->ShowVersionForm($versionID)
355
			))->renderWith(array(
356
				static::class . '_EditForm',
357
				'LeftAndMain_Content'
358
			));
359
		}
360
361
		// non javascript, redirect the user to the page
362
		return $this->redirect(Controller::join_links(
363
			$this->Link('version'),
364
			$versionID
365
		));
366
	}
367
368
	/**
369
	 * @param int|null $versionID
370
	 * @return Form
371
	 */
372
	public function ShowVersionForm($versionID = null) {
373
		if(!$versionID) return null;
0 ignored issues
show
Bug Best Practice introduced by
The expression $versionID of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
374
375
		$id = $this->currentPageID();
376
		$form = $this->getEditForm($id, null, $versionID);
377
378
		return $form;
379
	}
380
381
	/**
382
	 * @param int $versionID
383
	 * @param int $otherVersionID
384
	 * @return mixed
385
	 */
386
	public function CompareVersionsForm($versionID, $otherVersionID) {
387
		if($versionID > $otherVersionID) {
388
			$toVersion = $versionID;
389
			$fromVersion = $otherVersionID;
390
		} else {
391
			$toVersion = $otherVersionID;
392
			$fromVersion = $versionID;
393
		}
394
395
		if(!$toVersion || !$fromVersion) {
396
			return null;
397
		}
398
399
		$id = $this->currentPageID();
400
		/** @var SiteTree $page */
401
		$page = SiteTree::get()->byID($id);
402
403
		$record = null;
404
 		if($page && $page->exists()) {
405
			if(!$page->canView()) {
406
				return Security::permissionFailure($this);
407
			}
408
409
			$record = $page->compareVersions($fromVersion, $toVersion);
0 ignored issues
show
Documentation Bug introduced by
The method compareVersions does not exist on object<SilverStripe\CMS\Model\SiteTree>? 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...
410
		}
411
412
		$fromVersionRecord = Versioned::get_version('SilverStripe\\CMS\\Model\\SiteTree', $id, $fromVersion);
413
		$toVersionRecord = Versioned::get_version('SilverStripe\\CMS\\Model\\SiteTree', $id, $toVersion);
414
415
		if(!$fromVersionRecord) {
416
			user_error("Can't find version $fromVersion of page $id", E_USER_ERROR);
417
		}
418
419
		if(!$toVersionRecord) {
420
			user_error("Can't find version $toVersion of page $id", E_USER_ERROR);
421
		}
422
423
		if(!$record) {
424
			return null;
425
		}
426
		$form = $this->getEditForm($id, null, null, true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a integer|null.

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...
427
		$form->setActions(new FieldList());
428
		$form->addExtraClass('compare');
429
430
		// Comparison views shouldn't be editable.
431
		// Its important to convert fields *before* loading data,
432
		// as the comparison output is HTML and not valid values for the various field types
433
		$readonlyFields = $form->Fields()->makeReadonly();
434
		$form->setFields($readonlyFields);
435
436
		$form->loadDataFrom($record);
437
		$form->loadDataFrom(array(
438
			"ID" => $id,
439
			"Version" => $fromVersion,
440
		));
441
442
		foreach($form->Fields()->dataFields() as $field) {
443
			$field->dontEscape = true;
444
		}
445
446
		return $form;
447
	}
448
449
	public function Breadcrumbs($unlinked = false) {
450
		$crumbs = parent::Breadcrumbs($unlinked);
451
		$crumbs[0]->Title = _t('CMSPagesController.MENUTITLE');
452
		return $crumbs;
453
	}
454
455
}
456