Completed
Push — master ( 25a8fb...29fc7a )
by Hamish
12s
created

RootURLController::handleRequest()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 24
Code Lines 14

Duplication

Lines 4
Ratio 16.67 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 4
loc 24
rs 8.5125
c 2
b 0
f 0
cc 5
eloc 14
nc 3
nop 2
1
<?php
2
3
namespace SilverStripe\CMS\Controllers;
4
5
use SilverStripe\CMS\Model\SiteTree;
6
use SilverStripe\ORM\DataModel;
7
use SilverStripe\ORM\DB;
8
use Controller;
9
use SS_HTTPResponse;
10
use Translatable;
11
use Config;
12
use Deprecation;
13
use SS_HTTPRequest;
14
use ClassInfo;
15
use Director;
16
17
18
/**
19
 * @package cms
20
 * @subpackage control
21
 */
22
class RootURLController extends Controller {
23
24
	/**
25
	 * @var bool
26
	 */
27
	protected static $is_at_root = false;
28
29
	/**
30
	 * @config
31
	 * @var string
32
	 */
33
	private static $default_homepage_link = 'home';
34
35
	/**
36
	 * @var string
37
	 */
38
	protected static $cached_homepage_link;
39
40
	/**
41
	 * Get the full form (e.g. /home/) relative link to the home page for the current HTTP_HOST value. Note that the
42
	 * link is trimmed of leading and trailing slashes before returning to ensure consistency.
43
	 *
44
	 * @return string
45
	 */
46
	static public function get_homepage_link() {
47
		if(!self::$cached_homepage_link) {
48
			// @todo Move to 'homepagefordomain' module
49
			if(class_exists('HomepageForDomainExtension')) {
50
				$host       = str_replace('www.', null, $_SERVER['HTTP_HOST']);
51
				$candidates = SiteTree::get()->where(array(
52
					'"SiteTree"."HomepageForDomain" LIKE ?' => "%$host%"
53
				));
54
				if($candidates) foreach($candidates as $candidate) {
55
					if(preg_match('/(,|^) *' . preg_quote($host) . ' *(,|$)/', $candidate->HomepageForDomain)) {
56
						self::$cached_homepage_link = trim($candidate->RelativeLink(true), '/');
57
					}
58
				}
59
			}
60
61
			if(!self::$cached_homepage_link) {
62
				// TODO Move to 'translatable' module
63
				if (
64
					class_exists('Translatable')
65
					&& SiteTree::has_extension('Translatable')
66
					&& $link = Translatable::get_homepage_link_by_locale(Translatable::get_current_locale())
67
				) {
68
					self::$cached_homepage_link = $link;
69
				} else {
70
					self::$cached_homepage_link = Config::inst()->get('SilverStripe\\CMS\\Controllers\\RootURLController', 'default_homepage_link');
71
				}
72
			}
73
		}
74
75
		return self::$cached_homepage_link;
76
	}
77
78
	/**
79
	 * Set the URL Segment used for your homepage when it is created by dev/build.
80
	 * This allows you to use home page URLs other than the default "home".
81
	 *
82
	 * @deprecated 4.0 Use the "RootURLController.default_homepage_link" config setting instead
83
	 * @param string $urlsegment the URL segment for your home page
84
	 */
85
	static public function set_default_homepage_link($urlsegment = "home") {
86
		Deprecation::notice('4.0', 'Use the "RootURLController.default_homepage_link" config setting instead');
87
		Config::inst()->update('SilverStripe\\CMS\\Controllers\\RootURLController', 'default_homepage_link', $urlsegment);
88
	}
89
90
	/**
91
	 * Gets the link that denotes the homepage if there is not one explicitly defined for this HTTP_HOST value.
92
	 *
93
	 * @deprecated 4.0 Use the "RootURLController.default_homepage_link" config setting instead
94
	 * @return string
95
	 */
96
	static public function get_default_homepage_link() {
97
		Deprecation::notice('4.0', 'Use the "RootURLController.default_homepage_link" config setting instead');
98
		return Config::inst()->get('SilverStripe\\CMS\\Controllers\\RootURLController', 'default_homepage_link');
99
	}
100
101
	/**
102
	 * Returns TRUE if a request to a certain page should be redirected to the site root (i.e. if the page acts as the
103
	 * home page).
104
	 *
105
	 * @param SiteTree $page
106
	 * @return bool
107
	 */
108
	static public function should_be_on_root(SiteTree $page) {
109
		if(!self::$is_at_root && self::get_homepage_link() == trim($page->RelativeLink(true), '/')) {
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|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...
110
			return !(
111
				class_exists('Translatable')
112
					&& $page->hasExtension('Translatable')
113
					&& $page->Locale
0 ignored issues
show
Documentation introduced by
The property Locale does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
114
					&& $page->Locale != Translatable::default_locale()
0 ignored issues
show
Documentation introduced by
The property Locale does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
115
			);
116
		}
117
118
		return false;
119
	}
120
121
	/**
122
	 * Resets the cached homepage link value - useful for testing.
123
	 */
124
	static public function reset() {
125
		self::$cached_homepage_link = null;
126
	}
127
128 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...
129
		parent::beforeHandleRequest($request, $model);
130
131
		self::$is_at_root = true;
132
133
		/** @skipUpgrade */
134
		if(!DB::is_active() || !ClassInfo::hasTable('SiteTree')) {
135
			$this->getResponse()->redirect(Controller::join_links(
136
				Director::absoluteBaseURL(),
137
				'dev/build',
138
				'?' . http_build_query(array(
139
					'returnURL' => isset($_GET['url']) ? $_GET['url'] : null,
140
				))
141
			));
142
		}
143
	}
144
145
	/**
146
	 * @param SS_HTTPRequest $request
147
	 * @param DataModel|null $model
148
	 * @return SS_HTTPResponse
149
	 */
150
	public function handleRequest(SS_HTTPRequest $request, DataModel $model = null) {
151
		self::$is_at_root = true;
152
		$this->beforeHandleRequest($request, $model);
0 ignored issues
show
Bug introduced by
It seems like $model defined by parameter $model on line 150 can be null; however, SilverStripe\CMS\Control...::beforeHandleRequest() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
153
154
		if (!$this->getResponse()->isFinished()) {
155
			/** @skipUpgrade */
156 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...
157
				$this->getResponse()->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
158
				return $this->getResponse();
159
			}
160
161
			$request->setUrl(self::get_homepage_link() . '/');
162
			$request->match('$URLSegment//$Action', true);
163
			$controller = new ModelAsController();
164
165
			$response = $controller->handleRequest($request, $model);
166
167
			$this->prepareResponse($response);
168
		}
169
170
		$this->afterHandleRequest();
171
172
		return $this->getResponse();
173
	}
174
175
}
176