Completed
Push — master ( 4923a2...1efb32 )
by Damian
02:25
created

RootURLController::get_default_homepage_link()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
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\HTTPRequest;
9
use SilverStripe\Control\HTTPResponse;
10
use SilverStripe\Core\ClassInfo;
11
use SilverStripe\Core\Config\Config;
12
use SilverStripe\Core\Resettable;
13
use SilverStripe\Dev\Deprecation;
14
use SilverStripe\ORM\DataModel;
15
use SilverStripe\ORM\DB;
16
use Translatable;
17
18
class RootURLController extends Controller implements Resettable
19
{
20
21
    /**
22
     * @var bool
23
     */
24
    protected static $is_at_root = false;
25
26
    /**
27
     * @config
28
     * @var string
29
     */
30
    private static $default_homepage_link = 'home';
31
32
    /**
33
     * @var string
34
     */
35
    protected static $cached_homepage_link;
36
37
    /**
38
     * Get the full form (e.g. /home/) relative link to the home page for the current HTTP_HOST value. Note that the
39
     * link is trimmed of leading and trailing slashes before returning to ensure consistency.
40
     *
41
     * @return string
42
     */
43
    public static function get_homepage_link()
44
    {
45
        if (!self::$cached_homepage_link) {
46
            // @todo Move to 'homepagefordomain' module
47
            if (class_exists('HomepageForDomainExtension')) {
48
                $host       = str_replace('www.', null, $_SERVER['HTTP_HOST']);
49
                $candidates = SiteTree::get()->where(array(
50
                    '"SiteTree"."HomepageForDomain" LIKE ?' => "%$host%"
51
                ));
52
                if ($candidates) {
53
                    foreach ($candidates as $candidate) {
54
                        if (preg_match('/(,|^) *' . preg_quote($host) . ' *(,|$)/', $candidate->HomepageForDomain)) {
55
                            self::$cached_homepage_link = trim($candidate->RelativeLink(true), '/');
56
                        }
57
                    }
58
                }
59
            }
60
61
            if (!self::$cached_homepage_link) {
62
                // TODO Move to 'translatable' module
63
                if (class_exists('Translatable')
64
                    && SiteTree::has_extension('Translatable')
65
                    && $link = Translatable::get_homepage_link_by_locale(Translatable::get_current_locale())
66
                ) {
67
                    self::$cached_homepage_link = $link;
68
                } else {
69
                    self::$cached_homepage_link = Config::inst()->get('SilverStripe\\CMS\\Controllers\\RootURLController', 'default_homepage_link');
70
                }
71
            }
72
        }
73
74
        return self::$cached_homepage_link;
75
    }
76
77
    /**
78
     * Returns TRUE if a request to a certain page should be redirected to the site root (i.e. if the page acts as the
79
     * home page).
80
     *
81
     * @param SiteTree $page
82
     * @return bool
83
     */
84
    public static function should_be_on_root(SiteTree $page)
85
    {
86
        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...
87
            return !(
88
                class_exists('Translatable')
89
                    && $page->hasExtension('Translatable')
90
                    && $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...
91
                    && $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...
92
            );
93
        }
94
95
        return false;
96
    }
97
98
    /**
99
     * Resets the cached homepage link value - useful for testing.
100
     */
101
    public static function reset()
102
    {
103
        self::$cached_homepage_link = null;
104
    }
105
106 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...
107
    {
108
        parent::beforeHandleRequest($request, $model);
109
110
        self::$is_at_root = true;
111
112
        /** @skipUpgrade */
113
        if (!DB::is_active() || !ClassInfo::hasTable('SiteTree')) {
114
            $this->getResponse()->redirect(Controller::join_links(
115
                Director::absoluteBaseURL(),
116
                'dev/build',
117
                '?' . http_build_query(array(
118
                    'returnURL' => isset($_GET['url']) ? $_GET['url'] : null,
119
                ))
120
            ));
121
        }
122
    }
123
124
    /**
125
     * @param HTTPRequest $request
126
     * @param DataModel|null $model
127
     * @return HTTPResponse
128
     */
129
    public function handleRequest(HTTPRequest $request, DataModel $model = null)
130
    {
131
        self::$is_at_root = true;
132
        $this->beforeHandleRequest($request, $model);
0 ignored issues
show
Bug introduced by
It seems like $model defined by parameter $model on line 129 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...
133
134
        if (!$this->getResponse()->isFinished()) {
135
            /** @skipUpgrade */
136 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...
137
                $this->getResponse()->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
138
                return $this->getResponse();
139
            }
140
141
            $request->setUrl(self::get_homepage_link() . '/');
142
            $request->match('$URLSegment//$Action', true);
143
            $controller = new ModelAsController();
144
145
            $response = $controller->handleRequest($request, $model);
0 ignored issues
show
Bug introduced by
It seems like $model defined by parameter $model on line 129 can be null; however, SilverStripe\CMS\Control...roller::handleRequest() 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...
146
147
            $this->prepareResponse($response);
148
        }
149
150
        $this->afterHandleRequest();
151
152
        return $this->getResponse();
153
    }
154
}
155