Completed
Pull Request — master (#1352)
by
unknown
02:40
created

ModelAsController::getNestedController()   D

Complexity

Conditions 9
Paths 65

Size

Total Lines 34
Code Lines 16

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 34
rs 4.9091
cc 9
eloc 16
nc 65
nop 0
1
<?php
2
/**
3
 * ModelAsController deals with mapping the initial request to the first {@link SiteTree}/{@link ContentController}
4
 * pair, which are then used to handle the request.
5
 *
6
 * @package cms
7
 * @subpackage control
8
 */
9
class ModelAsController extends Controller implements NestedController {
10
	private static $extensions = array('OldPageRedirector');
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
12
	/**
13
	 * Get the appropriate {@link ContentController} for handling a {@link SiteTree} object, link it to the object and
14
	 * return it.
15
	 *
16
	 * @param SiteTree $sitetree
17
	 * @param string $action
18
	 * @return ContentController
19
	 */
20
	public static function controller_for(SiteTree $sitetree, $action = null) {
21
		if ($sitetree->class == 'SiteTree') {
22
			$controller = "ContentController";
23
		} else {
24
			$ancestry = ClassInfo::ancestry($sitetree->class);
25
			while ($class = array_pop($ancestry)) {
26
				if (class_exists($class . "_Controller")) break;
27
			}
28
			$controller = ($class !== null) ? "{$class}_Controller" : "ContentController";
29
		}
30
31
		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...
32
			$controller = $controller . '_' . ucfirst($action);
33
		}
34
35
		return class_exists($controller) ? Injector::inst()->create($controller, $sitetree) : $sitetree;
36
	}
37
38
	public function init() {
39
		singleton('SiteTree')->extend('modelascontrollerInit', $this);
40
		parent::init();
41
	}
42
43
	/**
44
	 * @uses ModelAsController::getNestedController()
45
	 * @param SS_HTTPRequest $request
46
	 * @param DataModel $model
47
	 * @return SS_HTTPResponse
48
	 */
49
	public function handleRequest(SS_HTTPRequest $request, DataModel $model) {
50
		$this->setRequest($request);
51
		$this->setDataModel($model);
52
53
		$this->pushCurrent();
54
		$this->getResponse();
55
		$this->init();
56
57
		// If we had a redirection or something, halt processing.
58
		if($this->getResponse()->isFinished()) {
59
			$this->popCurrent();
60
			return $this->getResponse();
61
		}
62
63
		// If the database has not yet been created, redirect to the build page.
64 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...
65
			$this->getResponse()->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
66
			$this->popCurrent();
67
68
			return $this->getResponse();
69
		}
70
71
		try {
72
			$result = $this->getNestedController();
73
74
			if($result instanceof RequestHandler) {
75
				$result = $result->handleRequest($this->getRequest(), $model);
76
			} else if(!($result instanceof SS_HTTPResponse)) {
77
				user_error("ModelAsController::getNestedController() returned bad object type '" .
78
					get_class($result)."'", E_USER_WARNING);
79
			}
80
		} catch(SS_HTTPResponse_Exception $responseException) {
81
			$result = $responseException->getResponse();
82
		}
83
84
		$this->popCurrent();
85
		return $result;
86
	}
87
88
	/**
89
	 * @return ContentController
90
	 * @throws Exception If URLSegment not passed in as a request parameter.
91
	 */
92
	public function getNestedController() {
93
		$request = $this->getRequest();
94
95
		if(!$URLSegment = $request->param('URLSegment')) {
96
			throw new Exception('ModelAsController->getNestedController(): was not passed a URLSegment value.');
97
		}
98
99
		// Find page by link, regardless of current locale settings
100
		if(class_exists('Translatable')) Translatable::disable_locale_filter();
101
102
		// Select child page
103
		$conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment));
104
		if(SiteTree::config()->nested_urls) {
105
			$conditions[] = array('"SiteTree"."ParentID"' => 0);
106
		}
107
		$sitetree = DataObject::get_one('SiteTree', $conditions);
108
109
		// Check translation module
110
		// @todo Refactor out module specific code
111
		if(class_exists('Translatable')) Translatable::enable_locale_filter();
112
113
		if(!$sitetree) {
114
			$this->httpError(404, 'The requested page could not be found.');
115
		}
116
117
		// Enforce current locale setting to the loaded SiteTree object
118
		if(class_exists('Translatable') && $sitetree->Locale) Translatable::set_current_locale($sitetree->Locale);
119
120
		if(isset($_REQUEST['debug'])) {
121
			Debug::message("Using record #$sitetree->ID of type $sitetree->class with link {$sitetree->Link()}");
122
		}
123
124
		return self::controller_for($sitetree, $this->getRequest()->param('Action'));
0 ignored issues
show
Compatibility introduced by
$sitetree of type object<DataObject> is not a sub-type of object<SiteTree>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
125
	}
126
127
	/**
128
	 * @deprecated 4.0 Use OldPageRedirector::find_old_page instead
129
	 *
130
	 * @param string $URLSegment A subset of the url. i.e in /home/contact/ home and contact are URLSegment.
131
	 * @param int $parent The ID of the parent of the page the URLSegment belongs to.
132
	 * @param bool $ignoreNestedURLs
133
	 * @return SiteTree
134
	 */
135
	static public function find_old_page($URLSegment, $parent = null, $ignoreNestedURLs = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $ignoreNestedURLs 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...
136
		Deprecation::notice('4.0', 'Use OldPageRedirector::find_old_page instead');
137
		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...
138
			$parent = SiteTree::get()->byId($parent);
139
		}
140
		$url = OldPageRedirector::find_old_page(array($URLSegment), $parent);
0 ignored issues
show
Bug introduced by
It seems like $parent can also be of type integer or object<DataObject>; however, OldPageRedirector::find_old_page() does only seem to accept object<SiteTree>|null, 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...
141
		return SiteTree::get_by_link($url);
0 ignored issues
show
Bug introduced by
It seems like $url defined by \OldPageRedirector::find...($URLSegment), $parent) on line 140 can also be of type boolean; however, SiteTree::get_by_link() does only seem to accept string, 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...
142
	}
143
}
144