Passed
Pull Request — master (#105)
by Daniel
02:12
created

Publisher::generatePageResponse()   F

Complexity

Conditions 12
Paths 504

Size

Total Lines 70
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
cc 12
eloc 49
c 8
b 0
f 0
nc 504
nop 1
dl 0
loc 70
rs 3.4888

How to fix   Long Method    Complexity   

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