Passed
Push — master ( fe986e...c3bca1 )
by Nicolaas
10:25
created

ControllerExtension   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 38
c 2
b 0
f 0
dl 0
loc 55
rs 10
wmc 16

1 Method

Rating   Name   Duplication   Size   Complexity  
C onBeforeInit() 0 51 15
1
<?php
2
3
namespace Sunnysideup\SimpleTemplateCaching\Extensions;
4
5
use SilverStripe\CMS\Controllers\ContentController;
6
use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware;
7
use SilverStripe\Core\Extension;
8
use SilverStripe\Security\Security;
9
use SilverStripe\SiteConfig\SiteConfig;
10
use SilverStripe\Versioned\Versioned;
11
12
/**
13
 * Class \ControllerExtension.
14
 *
15
 * @property ControllerExtension $owner
16
 */
17
class ControllerExtension extends Extension
18
{
19
    public function onBeforeInit()
20
    {
21
        if(Security::getCurrentUser()) {
22
            return;
23
        }
24
        if (Versioned::LIVE !== Versioned::get_stage()) {
25
            return;
26
        }
27
        /** PageController|ControllerExtension $owner */
28
        $owner = $this->getOwner();
29
        if ($owner instanceof ContentController) {
30
            $extend = $owner->extend('updateCacheControl');
31
            if($extend) {
32
                return;
33
            }
34
            $sc = SiteConfig::current_site_config();
35
            if(! $sc->HasCaching) {
36
                return;
37
            }
38
            $request = $owner->getRequest();
39
            if($request->param('Action')) {
40
                return;
41
            }
42
            if($request->param('ID')) {
43
                return;
44
            }
45
            if($request->isAjax()) {
46
                return;
47
            }
48
            if($request->getVar('flush')) {
49
                return;
50
            }
51
            if($request->requestVars()) {
52
                return;
53
            }
54
            $dataRecord = $owner->data();
55
            if (empty($dataRecord)) {
56
                return;
57
            }
58
            if($dataRecord->NeverCachePublicly) {
59
                HTTPCacheControlMiddleware::singleton()
60
                ->disableCache()
61
                ;
62
                return;
63
            }
64
            $cacheTime = (int) ($dataRecord->PublicCacheDurationInSeconds ?: $sc->PublicCacheDurationInSeconds);
65
            if($cacheTime > 0) {
66
                return HTTPCacheControlMiddleware::singleton()
67
                    ->enableCache()
68
                    ->setMaxAge($cacheTime)
69
                    ->publicCache(true)
70
                ;
71
            }
72
        }
73
    }
74
}
75