Passed
Pull Request — master (#70)
by Daniel
02:36
created

Publisher::generatePHPCacheRedirection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 2
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\StaticPublishQueue;
4
5
use SilverStripe\Control\Director;
6
use SilverStripe\Control\HTTPApplication;
7
use SilverStripe\Control\HTTPRequestBuilder;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Control\HTTPResponse_Exception;
10
use SilverStripe\Core\Config\Configurable;
11
use SilverStripe\Core\CoreKernel;
12
use SilverStripe\Core\Injector\Injectable;
13
use SilverStripe\Core\Manifest\ModuleLoader;
14
use SilverStripe\ORM\DataObject;
15
use SilverStripe\ORM\FieldType\DBDatetime;
16
use SilverStripe\ORM\FieldType\DBField;
17
use SilverStripe\StaticPublishQueue\Contract\StaticPublisher;
18
use SilverStripe\View\ArrayData;
19
use SilverStripe\View\Requirements;
20
use SilverStripe\View\Requirements_Backend;
21
use SilverStripe\View\SSViewer;
22
23
abstract class Publisher implements StaticPublisher
24
{
25
    use Injectable;
26
    use Configurable;
27
28
    /**
29
     * @var array
30
     * @config
31
     */
32
    private static $static_publisher_themes = [];
0 ignored issues
show
introduced by
The private property $static_publisher_themes is not used, and could be removed.
Loading history...
33
34
    /**
35
     * @config
36
     *
37
     * @var Boolean Use domain based caching (put cache files into a domain subfolder)
38
     * This must be true if you are using this with the "subsites" module.
39
     * Please note that this form of caching requires all URLs to be provided absolute
40
     * (not relative to the webroot) via {@link SiteTree->AbsoluteLink()}.
41
     */
42
    private static $domain_based_caching = false;
0 ignored issues
show
introduced by
The private property $domain_based_caching is not used, and could be removed.
Loading history...
43
44
    /**
45
     * @param string $url
46
     * @return HTTPResponse
47
     */
48
    public function generatePageResponse($url)
49
    {
50
        if (Director::is_relative_url($url)) {
51
            $url = Director::absoluteURL($url);
52
        }
53
        $urlParts = parse_url($url);
54
        if (!empty($urlParts['query'])) {
55
            parse_str($urlParts['query'], $getVars);
56
        } else {
57
            $getVars = [];
58
        }
59
        // back up requirements backend
60
        $origRequirements = Requirements::backend();
61
        Requirements::set_backend(Requirements_Backend::create());
62
63
        $origThemes = SSViewer::get_themes();
64
        $staticThemes = self::config()->get('static_publisher_themes');
65
        if ($staticThemes) {
66
            SSViewer::set_themes($staticThemes);
67
        } else {
68
            // get the themes raw from config to prevent the "running from the CMS" problem where no themes are live
69
            $rawThemes = SSViewer::config()->uninherited('themes');
70
            SSViewer::set_themes($rawThemes);
71
        }
72
        try {
73
            // try to add all the server vars that would be needed to create a static cache
74
            $request = HTTPRequestBuilder::createFromVariables(
75
                [
76
                '_SERVER' => [
77
                    'REQUEST_URI' => isset($urlParts['path']) ? $urlParts['path'] : '',
78
                    'REQUEST_METHOD' => 'GET',
79
                    'REMOTE_ADDR' => '127.0.0.1',
80
                    'HTTPS' => $urlParts['scheme'] == 'https' ? 'on' : 'off',
81
                    'QUERY_STRING' => isset($urlParts['query']) ? $urlParts['query'] : '',
82
                    'REQUEST_TIME' => DBDatetime::now()->getTimestamp(),
83
                    'REQUEST_TIME_FLOAT' => (float) DBDatetime::now()->getTimestamp(),
84
                    'HTTP_HOST' => $urlParts['host'],
85
                    'HTTP_USER_AGENT' => 'silverstripe/staticpublishqueue',
86
                ],
87
                '_GET' => $getVars,
88
                '_POST' => [],
89
                ],
90
                ''
91
            );
92
            $app = $this->getHTTPApplication();
93
            $response = $app->handle($request);
94
        } catch (HTTPResponse_Exception $e) {
95
            $response = $e->getResponse();
96
        } finally {
97
            // restore backends
98
            SSViewer::set_themes($origThemes);
99
            Requirements::set_backend($origRequirements);
100
            DataObject::singleton()->flushCache();
101
        }
102
        return $response;
103
    }
104
105
    /**
106
     * @return HTTPApplication
107
     */
108
    protected function getHTTPApplication()
109
    {
110
        $kernel = new CoreKernel(BASE_PATH);
111
        return new HTTPApplication($kernel);
112
    }
113
114
    /**
115
     * Generate the templated content for a PHP script that can serve up the
116
     * given piece of content with the given age and expiry.
117
     *
118
     * @param HTTPResponse $response
119
     *
120
     * @return string
121
     */
122
    protected function generatePHPCacheFile($response)
123
    {
124
        $cacheConfig = [
125
            'responseCode' => $response->getStatusCode(),
126
            'headers' => [],
127
        ];
128
129
        foreach ($response->getHeaders() as $header => $value) {
130
            if (!in_array($header, [ 'cache-control' ])) {
131
                $cacheConfig['headers'][] = sprintf('%s: %s', $header, $value);
132
            }
133
        }
134
135
        return "<?php\n\nreturn " . var_export($cacheConfig, true) . ';';
136
    }
137
138
    /**
139
     * @param string $destination
140
     * @return string
141
     */
142
    protected function generateHTMLCacheRedirection($destination)
143
    {
144
        return SSViewer::execute_template(
145
            'SilverStripe\\StaticPublishQueue\\HTMLRedirection',
146
            ArrayData::create([
147
                'URL' => DBField::create_field('Varchar', $destination),
148
            ])
149
        );
150
    }
151
}
152