Completed
Push — master ( 38e111...ab04a4 )
by Matthew
02:26
created

ControllerExtension   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 44
ccs 0
cts 17
cp 0
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A renderWithLayout() 0 14 1
A getLayoutTemplates() 0 16 3
1
<?php
2
3
namespace Dynamic\ViewableDataObject\Extensions;
4
5
use SilverStripe\Core\Extension;
6
use SilverStripe\View\SSViewer;
7
use SilverStripe\View\ThemeResourceLoader;
8
9
/**
10
 * Class ControllerExtension
11
 * @package Dynamic\ViewableDataObject\Extensions
12
 *
13
 * @property \SilverStripe\Control\Controller $owner
14
 */
15
class ControllerExtension extends Extension
16
{
17
    /**
18
     * @param array|string $templates
19
     * @param array|\SilverStripe\View\ArrayData $customFields
20
     * @return \SilverStripe\ORM\FieldType\DBHTMLText
21
     */
22
    public function renderWithLayout($templates, $customFields = [])
23
    {
24
        $templates = $this->getLayoutTemplates($templates);
25
26
        $this->owner->extend('updateLayoutFields', $customFields);
27
28
        $viewer = new SSViewer($this->owner->getViewerTemplates());
29
        $viewer->setTemplateFile('Layout', ThemeResourceLoader::inst()->findTemplate(
30
            $templates,
31
            SSViewer::get_themes()
32
        ));
33
34
        return $viewer->process(
35
            $this->owner->customise($customFields)
36
        );
37
    }
38
39
    /**
40
     * @param array|string $templates
41
     * @return array
42
     */
43
    private function getLayoutTemplates($templates)
44
    {
45
        if (is_string($templates)) {
46
            $templates = [$templates];
47
        }
48
49
        // Always include page template as fallback
50
        if ($templates[count($templates) - 1] !== \Page::class) {
51
            array_push($templates, \Page::class);
52
        }
53
54
        // otherwise it renders funny
55
        $templates = ['type' => 'Layout'] + $templates;
56
        $this->owner->extend('updateLayoutTemplates', $templates);
57
58
        return $templates;
59
    }
60
}
61