Completed
Push — master ( 2fcfce...de1d77 )
by Robbie
11s
created

ShareDraftController::preview()   B

Complexity

Conditions 6
Paths 22

Size

Total Lines 71
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 43
nc 22
nop 1
dl 0
loc 71
rs 8.5309
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace SilverStripe\ShareDraftContent\Controllers;
4
5
use BadMethodCallException;
6
use Exception;
7
use PageController;
0 ignored issues
show
Bug introduced by
The type PageController was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use SilverStripe\CMS\Controllers\ModelAsController;
9
use SilverStripe\CMS\Model\SiteTree;
10
use SilverStripe\Control\Controller;
11
use SilverStripe\Control\HTTPRequest;
12
use SilverStripe\Control\Session;
13
use SilverStripe\Core\Injector\Injector;
14
use SilverStripe\ShareDraftContent\Models\ShareToken;
15
use SilverStripe\Versioned\Versioned;
16
use SilverStripe\View\ArrayData;
17
use SilverStripe\View\Requirements;
18
19
class ShareDraftController extends Controller
20
{
21
    /**
22
     * Controller for rendering draft pages.
23
     *
24
     * @config
25
     *
26
     * @var string
27
     */
28
    private static $controller = PageController::class;
0 ignored issues
show
introduced by
The private property $controller is not used, and could be removed.
Loading history...
29
30
    /**
31
     * @var array
32
     */
33
    private static $allowed_actions = array(
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
34
        'preview'
35
    );
36
37
    /**
38
     * @var array
39
     */
40
    private static $url_handlers = array(
0 ignored issues
show
introduced by
The private property $url_handlers is not used, and could be removed.
Loading history...
41
        '$Key/$Token' => 'preview'
42
    );
43
44
    /**
45
     * @param HTTPRequest $request
46
     *
47
     * @return string|HTMLText
0 ignored issues
show
Bug introduced by
The type SilverStripe\ShareDraftC...nt\Controllers\HTMLText was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
48
     */
49
    public function preview(HTTPRequest $request)
50
    {
51
        $key = $request->param('Key');
52
        $token = $request->param('Token');
53
        try {
54
            $session = $this->getRequest()->getSession();
55
        } catch (BadMethodCallException $e) {
56
            // Create a new session
57
            $session = $this->getRequest()
58
                ->setSession(Injector::inst()->create(Session::class, []))
59
                ->getSession();
60
        }
61
        /**
62
         * @var ShareToken $shareToken
63
         */
64
        $shareToken = ShareToken::get()->filter('Token', $token)->first();
65
66
        if (!$shareToken) {
67
            return $this->errorPage();
68
        }
69
70
        $page = Versioned::get_one_by_stage(
71
            SiteTree::class,
72
            'Stage',
73
            sprintf('"SiteTree"."ID" = \'%d\'', $shareToken->PageID)
74
        );
75
76
        $latest = Versioned::get_latest_version(SiteTree::class, $shareToken->PageID);
77
78
        $controller = $this->getControllerFor($page);
79
80
        if (!$shareToken->isExpired() && $page->generateKey($shareToken->Token) === $key) {
81
            Requirements::css('silverstripe/sharedraftcontent:css/top-bar.css');
82
83
            // Temporarily un-secure the draft site and switch to draft
84
            $oldSecured = $session->get('unsecuredDraftSite');
85
            $oldMode = Versioned::get_reading_mode();
86
            $restore = function () use ($oldSecured, $oldMode, $session) {
87
                $session->set('unsecuredDraftSite', $oldSecured);
88
                Versioned::set_reading_mode($oldMode);
89
            };
90
91
            // Process page inside an unsecured draft container
92
            try {
93
                $session->set('unsecuredDraftSite', true);
94
                Versioned::set_stage('Stage');
95
96
                // Hack to get around ContentController::init() redirecting on home page
97
                $_FILES = array(array());
98
99
                // Create mock request; Simplify request to single top level request
100
                $pageRequest = new HTTPRequest('GET', $page->URLSegment);
101
                $pageRequest->match('$URLSegment//$Action/$ID/$OtherID', true);
102
                $pageRequest->setSession($session);
103
                $rendered = $controller->handleRequest($pageRequest, $this->model);
104
105
                // Render draft heading
106
                $data = new ArrayData(array(
107
                    'Page' => $page,
108
                    'Latest' => $latest,
109
                ));
110
                $include = (string) $data->renderWith('Includes/TopBar');
111
            } catch (Exception $ex) {
112
                $restore();
113
                throw $ex;
114
            }
115
            $restore();
116
117
            return str_replace('</body>', $include . '</body>', (string) $rendered->getBody());
118
        } else {
119
            return $this->errorPage();
120
        }
121
    }
122
123
    /**
124
     * @return HTMLText
125
     */
126
    protected function errorPage()
127
    {
128
        Requirements::css('silverstripe/sharedraftcontent:css/error-page.css');
129
130
        return $this->renderWith('ShareDraftContentError');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->renderWith...hareDraftContentError') returns the type SilverStripe\ORM\FieldType\DBHTMLText which is incompatible with the documented return type SilverStripe\ShareDraftC...nt\Controllers\HTMLText.
Loading history...
131
    }
132
133
    /**
134
     * @param mixed $page
135
     *
136
     * @return mixed
137
     */
138
    protected function getControllerFor($page)
139
    {
140
        return ModelAsController::controller_for($page);
141
    }
142
}
143