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

ModelAsController::find_old_page()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 6
nc 2
nop 3
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
30
    private static $extensions = array('SilverStripe\\CMS\\Controllers\\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...
31
32
    /**
33
     * Get the appropriate {@link ContentController} for handling a {@link SiteTree} object, link it to the object and
34
     * return it.
35
     *
36
     * @param SiteTree $sitetree
37
     * @param string $action
38
     * @return ContentController
39
     */
40
    public static function controller_for(SiteTree $sitetree, $action = null)
41
    {
42
        $controller = $sitetree->getControllerName();
43
44
        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...
45
            $controller = $controller . '_' . ucfirst($action);
46
        }
47
48
        return Injector::inst()->create($controller, $sitetree);
49
    }
50
51
    protected function init()
52
    {
53
        singleton('SilverStripe\\CMS\\Model\\SiteTree')->extend('modelascontrollerInit', $this);
54
        parent::init();
55
    }
56
57 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...
58
    {
59
        parent::beforeHandleRequest($request, $model);
60
        // If the database has not yet been created, redirect to the build page.
61
        /** @skipUpgrade */
62
        if (!DB::is_active() || !ClassInfo::hasTable('SiteTree')) {
63
            $this->getResponse()->redirect(Controller::join_links(
64
                Director::absoluteBaseURL(),
65
                'dev/build',
66
                '?' . http_build_query(array(
67
                    'returnURL' => isset($_GET['url']) ? $_GET['url'] : null,
68
                ))
69
            ));
70
        }
71
    }
72
73
    /**
74
     * @uses ModelAsController::getNestedController()
75
     * @param HTTPRequest $request
76
     * @param DataModel $model
77
     * @return HTTPResponse
78
     */
79
    public function handleRequest(HTTPRequest $request, DataModel $model)
80
    {
81
        $this->beforeHandleRequest($request, $model);
82
83
        // If we had a redirection or something, halt processing.
84
        if ($this->getResponse()->isFinished()) {
85
            $this->popCurrent();
86
            return $this->getResponse();
87
        }
88
89
        // If the database has not yet been created, redirect to the build page.
90
        /** @skipUpgrade */
91 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...
92
            $this->getResponse()->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
93
            $this->popCurrent();
94
95
            return $this->getResponse();
96
        }
97
98
        try {
99
            $result = $this->getNestedController();
100
101
            if ($result instanceof RequestHandler) {
102
                $result = $result->handleRequest($this->getRequest(), $model);
103
            } elseif (!($result instanceof HTTPResponse)) {
104
                user_error("ModelAsController::getNestedController() returned bad object type '" .
105
                    get_class($result)."'", E_USER_WARNING);
106
            }
107
        } catch (HTTPResponse_Exception $responseException) {
108
            $result = $responseException->getResponse();
109
        }
110
111
        $this->popCurrent();
112
        return $result;
113
    }
114
115
    /**
116
     * @return ContentController
117
     * @throws Exception If URLSegment not passed in as a request parameter.
118
     */
119
    public function getNestedController()
120
    {
121
        $request = $this->getRequest();
122
123
        if (!$URLSegment = $request->param('URLSegment')) {
124
            throw new Exception('ModelAsController->getNestedController(): was not passed a URLSegment value.');
125
        }
126
127
        // Find page by link, regardless of current locale settings
128
        if (class_exists('Translatable')) {
129
            Translatable::disable_locale_filter();
130
        }
131
132
        // Select child page
133
        $conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment));
134
        if (SiteTree::config()->nested_urls) {
135
            $conditions[] = array('"SiteTree"."ParentID"' => 0);
136
        }
137
        /** @var SiteTree $sitetree */
138
        $sitetree = DataObject::get_one('SilverStripe\\CMS\\Model\\SiteTree', $conditions);
139
140
        // Check translation module
141
        // @todo Refactor out module specific code
142
        if (class_exists('Translatable')) {
143
            Translatable::enable_locale_filter();
144
        }
145
146
        if (!$sitetree) {
147
            $this->httpError(404, 'The requested page could not be found.');
148
        }
149
150
        // Enforce current locale setting to the loaded SiteTree object
151
        if (class_exists('Translatable') && $sitetree->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...
152
            Translatable::set_current_locale($sitetree->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...
153
        }
154
155
        if (isset($_REQUEST['debug'])) {
156
            Debug::message("Using record #$sitetree->ID of type " . get_class($sitetree) . " with link {$sitetree->Link()}");
157
        }
158
159
        return self::controller_for($sitetree, $this->getRequest()->param('Action'));
160
    }
161
}
162