Completed
Pull Request — master (#1605)
by Loz
03:02
created

ModelAsController::controller_for()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 4
rs 10
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace SilverStripe\CMS\Controllers;
4
5
use SilverStripe\CMS\Model\SiteTree;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Control\Director;
8
use SilverStripe\Control\NestedController;
9
use SilverStripe\Control\RequestHandler;
10
use SilverStripe\Control\SS_HTTPRequest;
11
use SilverStripe\Control\SS_HTTPResponse;
12
use SilverStripe\Control\SS_HTTPResponse_Exception;
13
use SilverStripe\Core\ClassInfo;
14
use SilverStripe\Core\Injector\Injector;
15
use SilverStripe\Dev\Debug;
16
use SilverStripe\Dev\Deprecation;
17
use SilverStripe\ORM\DataModel;
18
use SilverStripe\ORM\DataObject;
19
use SilverStripe\ORM\DB;
20
use Exception;
21
use Translatable;
22
23
/**
24
 * ModelAsController deals with mapping the initial request to the first {@link SiteTree}/{@link ContentController}
25
 * pair, which are then used to handle the request.
26
 */
27
class ModelAsController extends Controller implements NestedController {
28
29
	private static $extensions = array('SilverStripe\\CMS\\Controllers\\OldPageRedirector');
30
31
	/**
32
	 * Get the appropriate {@link ContentController} for handling a {@link SiteTree} object, link it to the object and
33
	 * return it.
34
	 *
35
	 * @deprecated 5.0
36
	 * @param SiteTree $sitetree
37
	 * @param string $action
38
	 * @return ContentController
39
	 */
40
	public static function controller_for(SiteTree $sitetree, $action = null) {
41
		Deprecation::notice('5.0', 'Use $sitetree->getAssociatedController() instead');
42
		return $sitetree->getAssociatedController($action);
43
	}
44
45
	public function init() {
46
		singleton('SilverStripe\\CMS\\Model\\SiteTree')->extend('modelascontrollerInit', $this);
47
		parent::init();
48
	}
49
50 View Code Duplication
	protected function beforeHandleRequest(SS_HTTPRequest $request, DataModel $model) {
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...
51
		parent::beforeHandleRequest($request, $model);
52
		// If the database has not yet been created, redirect to the build page.
53
		/** @skipUpgrade */
54
		if(!DB::is_active() || !ClassInfo::hasTable('SiteTree')) {
55
			$this->getResponse()->redirect(Controller::join_links(
56
				Director::absoluteBaseURL(),
57
				'dev/build',
58
				'?' . http_build_query(array(
59
					'returnURL' => isset($_GET['url']) ? $_GET['url'] : null,
60
				))
61
			));
62
		}
63
	}
64
65
	/**
66
	 * @uses ModelAsController::getNestedController()
67
	 * @param SS_HTTPRequest $request
68
	 * @param DataModel $model
69
	 * @return SS_HTTPResponse
70
	 */
71
	public function handleRequest(SS_HTTPRequest $request, DataModel $model) {
72
		$this->beforeHandleRequest($request, $model);
73
74
		// If we had a redirection or something, halt processing.
75
		if($this->getResponse()->isFinished()) {
76
			$this->popCurrent();
77
			return $this->getResponse();
78
		}
79
80
		// If the database has not yet been created, redirect to the build page.
81
		/** @skipUpgrade */
82 View Code Duplication
		if(!DB::is_active() || !ClassInfo::hasTable('SiteTree')) {
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...
83
			$this->getResponse()->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
84
			$this->popCurrent();
85
86
			return $this->getResponse();
87
		}
88
89
		try {
90
			$result = $this->getNestedController();
91
92
			if($result instanceof RequestHandler) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\Control\RequestHandler does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
93
				$result = $result->handleRequest($this->getRequest(), $model);
94
			} else if(!($result instanceof SS_HTTPResponse)) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\Control\SS_HTTPResponse does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
95
				user_error("ModelAsController::getNestedController() returned bad object type '" .
96
					get_class($result)."'", E_USER_WARNING);
97
			}
98
		} catch(SS_HTTPResponse_Exception $responseException) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\Control\SS_HTTPResponse_Exception 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...
99
			$result = $responseException->getResponse();
100
		}
101
102
		$this->popCurrent();
103
		return $result;
104
	}
105
106
	/**
107
	 * @return ContentController
108
	 * @throws Exception If URLSegment not passed in as a request parameter.
109
	 */
110
	public function getNestedController() {
111
		$request = $this->getRequest();
112
113
		if(!$URLSegment = $request->param('URLSegment')) {
114
			throw new Exception('ModelAsController->getNestedController(): was not passed a URLSegment value.');
115
		}
116
117
		// Find page by link, regardless of current locale settings
118
		if(class_exists('Translatable')) Translatable::disable_locale_filter();
119
120
		// Select child page
121
		$conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment));
122
		if(SiteTree::config()->nested_urls) {
123
			$conditions[] = array('"SiteTree"."ParentID"' => 0);
124
		}
125
		/** @var SiteTree $sitetree */
126
		$sitetree = DataObject::get_one('SilverStripe\\CMS\\Model\\SiteTree', $conditions);
127
128
		// Check translation module
129
		// @todo Refactor out module specific code
130
		if(class_exists('Translatable')) Translatable::enable_locale_filter();
131
132
		if(!$sitetree) {
133
			$this->httpError(404, 'The requested page could not be found.');
134
		}
135
136
		// Enforce current locale setting to the loaded SiteTree object
137
		if(class_exists('Translatable') && $sitetree->Locale) Translatable::set_current_locale($sitetree->Locale);
138
139
		if(isset($_REQUEST['debug'])) {
140
			Debug::message("Using record #$sitetree->ID of type $sitetree->class with link {$sitetree->Link()}");
141
		}
142
143
		return self::controller_for($sitetree, $this->getRequest()->param('Action'));
0 ignored issues
show
Deprecated Code introduced by
The method SilverStripe\CMS\Control...oller::controller_for() has been deprecated with message: 5.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
144
	}
145
146
	/**
147
	 * @deprecated 4.0 Use OldPageRedirector::find_old_page instead
148
	 *
149
	 * @param string $URLSegment A subset of the url. i.e in /home/contact/ home and contact are URLSegment.
150
	 * @param int $parent The ID of the parent of the page the URLSegment belongs to.
151
	 * @param bool $ignoreNestedURLs
152
	 * @return SiteTree
153
	 */
154
	static public function find_old_page($URLSegment, $parent = null, $ignoreNestedURLs = false) {
155
		Deprecation::notice('4.0', 'Use OldPageRedirector::find_old_page instead');
156
		if ($parent) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parent 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...
157
			$parent = SiteTree::get()->byID($parent);
158
		}
159
		$url = OldPageRedirector::find_old_page(array($URLSegment), $parent);
160
		return SiteTree::get_by_link($url);
161
	}
162
}
163