Completed
Pull Request — master (#1605)
by Loz
06:01 queued 03:07
created

ModelAsController::controller_for()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 5
nc 2
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\HTTPRequest;
11
use SilverStripe\Control\HTTPResponse;
12
use SilverStripe\Control\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
	 * @param SiteTree $sitetree
36
	 * @param string $action
37
	 * @return ContentController
38
	 */
39
	public static function controller_for(SiteTree $sitetree, $action = null) {
40
		$controller = $sitetree->getControllerName();
41
42
		if ($action && class_exists($controller . '_' . ucfirst($action))) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $action of type string|null is loosely compared to true; this is ambiguous if the string can be empty. 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 string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
43
			$controller = $controller . '_' . ucfirst($action);
44
		}
45
46
		return Injector::inst()->create($controller, $sitetree);
47
	}
48
49
	public function init() {
50
		singleton('SilverStripe\\CMS\\Model\\SiteTree')->extend('modelascontrollerInit', $this);
51
		parent::init();
52
	}
53
54 View Code Duplication
	protected function beforeHandleRequest(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...
55
		parent::beforeHandleRequest($request, $model);
56
		// If the database has not yet been created, redirect to the build page.
57
		/** @skipUpgrade */
58
		if(!DB::is_active() || !ClassInfo::hasTable('SiteTree')) {
59
			$this->getResponse()->redirect(Controller::join_links(
60
				Director::absoluteBaseURL(),
61
				'dev/build',
62
				'?' . http_build_query(array(
63
					'returnURL' => isset($_GET['url']) ? $_GET['url'] : null,
64
				))
65
			));
66
		}
67
	}
68
69
	/**
70
	 * @uses ModelAsController::getNestedController()
71
	 * @param HTTPRequest $request
72
	 * @param DataModel $model
73
	 * @return HTTPResponse
74
	 */
75
	public function handleRequest(HTTPRequest $request, DataModel $model) {
76
		$this->beforeHandleRequest($request, $model);
77
78
		// If we had a redirection or something, halt processing.
79
		if($this->getResponse()->isFinished()) {
80
			$this->popCurrent();
81
			return $this->getResponse();
82
		}
83
84
		// If the database has not yet been created, redirect to the build page.
85
		/** @skipUpgrade */
86 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...
87
			$this->getResponse()->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
88
			$this->popCurrent();
89
90
			return $this->getResponse();
91
		}
92
93
		try {
94
			$result = $this->getNestedController();
95
96
			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...
97
				$result = $result->handleRequest($this->getRequest(), $model);
98
			} else if(!($result instanceof HTTPResponse)) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\Control\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...
99
				user_error("ModelAsController::getNestedController() returned bad object type '" .
100
					get_class($result)."'", E_USER_WARNING);
101
			}
102
		} catch(HTTPResponse_Exception $responseException) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\Control\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...
103
			$result = $responseException->getResponse();
104
		}
105
106
		$this->popCurrent();
107
		return $result;
108
	}
109
110
	/**
111
	 * @return ContentController
112
	 * @throws Exception If URLSegment not passed in as a request parameter.
113
	 */
114
	public function getNestedController() {
115
		$request = $this->getRequest();
116
117
		if(!$URLSegment = $request->param('URLSegment')) {
118
			throw new Exception('ModelAsController->getNestedController(): was not passed a URLSegment value.');
119
		}
120
121
		// Find page by link, regardless of current locale settings
122
		if(class_exists('Translatable')) Translatable::disable_locale_filter();
123
124
		// Select child page
125
		$conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment));
126
		if(SiteTree::config()->nested_urls) {
127
			$conditions[] = array('"SiteTree"."ParentID"' => 0);
128
		}
129
		/** @var SiteTree $sitetree */
130
		$sitetree = DataObject::get_one('SilverStripe\\CMS\\Model\\SiteTree', $conditions);
131
132
		// Check translation module
133
		// @todo Refactor out module specific code
134
		if(class_exists('Translatable')) Translatable::enable_locale_filter();
135
136
		if(!$sitetree) {
137
			$this->httpError(404, 'The requested page could not be found.');
138
		}
139
140
		// Enforce current locale setting to the loaded SiteTree object
141
		if(class_exists('Translatable') && $sitetree->Locale) Translatable::set_current_locale($sitetree->Locale);
142
143
		if(isset($_REQUEST['debug'])) {
144
			Debug::message("Using record #$sitetree->ID of type $sitetree->class with link {$sitetree->Link()}");
145
		}
146
147
		return self::controller_for($sitetree, $this->getRequest()->param('Action'));
148
	}
149
150
	/**
151
	 * @deprecated 4.0 Use OldPageRedirector::find_old_page instead
152
	 *
153
	 * @param string $URLSegment A subset of the url. i.e in /home/contact/ home and contact are URLSegment.
154
	 * @param int $parent The ID of the parent of the page the URLSegment belongs to.
155
	 * @param bool $ignoreNestedURLs
156
	 * @return SiteTree
157
	 */
158
	static public function find_old_page($URLSegment, $parent = null, $ignoreNestedURLs = false) {
159
		Deprecation::notice('4.0', 'Use OldPageRedirector::find_old_page instead');
160
		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...
161
			$parent = SiteTree::get()->byID($parent);
162
		}
163
		$url = OldPageRedirector::find_old_page(array($URLSegment), $parent);
164
		return SiteTree::get_by_link($url);
165
	}
166
}
167