Passed
Push — master ( ba30ee...426ceb )
by Robbie
02:46
created

HistoryControllerFactory::create()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 4
nop 2
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\VersionedAdmin\Controllers;
4
5
use SilverStripe\CMS\Controllers\CMSPageHistoryController;
6
use SilverStripe\CMS\Model\SiteTree;
7
use SilverStripe\Control\HTTPRequest;
8
use SilverStripe\Core\Extensible;
9
use SilverStripe\Core\Injector\Factory;
10
use SilverStripe\Core\Injector\Injector;
11
use SilverStripe\Versioned\Versioned;
12
13
/**
14
 * The history controller factory decides which CMS history controller to use, out of the default from the
15
 * silverstripe/cms module or the history viewer controller from this module, depending on the current page type
16
 */
17
class HistoryControllerFactory implements Factory
18
{
19
    use Extensible;
20
21
    public function create($service, array $params = array())
22
    {
23
        // If no request is available yet, return the default controller
24
        if (!Injector::inst()->has(HTTPRequest::class)) {
25
            return new CMSPageHistoryController();
26
        }
27
        $request = Injector::inst()->get(HTTPRequest::class);
28
        $id = $request->param('ID');
29
30
        if ($id) {
31
            // Ensure we read from the draft stage at this position
32
            $originalStage = Versioned::get_stage();
33
            Versioned::set_stage(Versioned::DRAFT);
34
            $page = SiteTree::get()->byID($id);
35
            Versioned::set_stage($originalStage);
36
37
            if ($page && $this->isEnabled($page)) {
38
                return Injector::inst()->create(CMSPageHistoryViewerController::class);
39
            }
40
        }
41
42
        // Injector is not used to prevent an infinite loop
43
        return new CMSPageHistoryController();
44
    }
45
46
    /**
47
     * Only activate for pages that have a history viewer capability applied. Extensions can provide their
48
     * own two cents about this criteria.
49
     *
50
     * @param SiteTree $record
51
     * @return bool
52
     */
53
    public function isEnabled(SiteTree $record)
54
    {
55
        $enabledResults = array_filter($this->extend('updateIsEnabled', $record));
56
        return (!empty($enabledResults) && max($enabledResults) === true);
57
    }
58
}
59