Passed
Push — master ( c5d65d...3bc83b )
by
unknown
02:05
created

FilesystemPublisher   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 228
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 99
dl 0
loc 228
rs 8.96
c 0
b 0
f 0
wmc 43

14 Methods

Rating   Name   Duplication   Size   Complexity  
A getFileExtension() 0 3 1
A getDestFolder() 0 3 1
A setDestFolder() 0 4 1
A getDestPath() 0 4 2
A publishRedirect() 0 12 4
A publishPage() 0 11 4
A setFileExtension() 0 15 2
A purgeURL() 0 18 4
B publishURL() 0 26 7
B getPublishedURLs() 0 23 7
A deleteFromPath() 0 10 2
A saveToPath() 0 17 3
A pathToURL() 0 17 4
A URLtoPath() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like FilesystemPublisher often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FilesystemPublisher, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace SilverStripe\StaticPublishQueue\Publisher;
4
5
use SilverStripe\Assets\Filesystem;
6
use SilverStripe\Control\Director;
7
use SilverStripe\Control\HTTPResponse;
8
use SilverStripe\StaticPublishQueue\Publisher;
9
use function SilverStripe\StaticPublishQueue\URLtoPath;
10
11
class FilesystemPublisher extends Publisher
12
{
13
    /**
14
     * @var string
15
     */
16
    protected $destFolder = 'cache';
17
18
    /**
19
     * @var string
20
     */
21
    protected $fileExtension = 'php';
22
23
    /**
24
     * @return string
25
     */
26
    public function getDestPath()
27
    {
28
        $base = defined('PUBLIC_PATH') ? PUBLIC_PATH : BASE_PATH;
29
        return $base . DIRECTORY_SEPARATOR . $this->getDestFolder();
30
    }
31
32
    public function setDestFolder($destFolder)
33
    {
34
        $this->destFolder = $destFolder;
35
        return $this;
36
    }
37
38
    public function getDestFolder()
39
    {
40
        return $this->destFolder;
41
    }
42
43
    public function setFileExtension($fileExtension)
44
    {
45
        $fileExtension = strtolower($fileExtension);
46
        if (!in_array($fileExtension, ['html', 'php'])) {
47
            throw new \InvalidArgumentException(
48
                sprintf(
49
                    'Bad file extension "%s" passed to %s::%s',
50
                    $fileExtension,
51
                    static::class,
52
                    __FUNCTION__
53
                )
54
            );
55
        }
56
        $this->fileExtension = $fileExtension;
57
        return $this;
58
    }
59
60
    public function getFileExtension()
61
    {
62
        return $this->fileExtension;
63
    }
64
65
    public function purgeURL($url)
66
    {
67
        if (!$url) {
68
            user_error("Bad url:" . var_export($url, true), E_USER_WARNING);
69
            return;
70
        }
71
        if ($path = $this->URLtoPath($url)) {
72
            $success = $this->deleteFromPath($path . '.html') && $this->deleteFromPath($path . '.php');
73
            return [
74
                'success' => $success,
75
                'url' => $url,
76
                'path' => $this->getDestPath() . DIRECTORY_SEPARATOR . $path,
77
            ];
78
        }
79
        return [
80
            'success' => false,
81
            'url' => $url,
82
            'path' => false,
83
        ];
84
    }
85
86
    /**
87
     * @param string $url
88
     * @return array A result array
89
     */
90
    public function publishURL($url, $forcePublish = false)
91
    {
92
        if (!$url) {
93
            user_error("Bad url:" . var_export($url, true), E_USER_WARNING);
94
            return;
95
        }
96
        $success = false;
97
        $response = $this->generatePageResponse($url);
98
        $statusCode = $response->getStatusCode();
99
        $doPublish = ($forcePublish && $this->getFileExtension() == 'php') || $statusCode < 400;
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: $doPublish = ($forcePubl...' || $statusCode < 400), Probably Intended Meaning: $doPublish = $forcePubli...' || $statusCode < 400)
Loading history...
100
101
        if ($statusCode < 300) {
102
            // publish success response
103
            $success = $this->publishPage($response, $url);
104
        } elseif ($statusCode < 400) {
105
            // publish redirect response
106
            $success = $this->publishRedirect($response, $url);
107
        } elseif ($doPublish) {
108
            // only publish error pages if we are able to send status codes via PHP
109
            $success = $this->publishPage($response, $url);
110
        }
111
        return [
112
            'published' => $doPublish,
113
            'success' => $success,
114
            'responsecode' => $statusCode,
115
            'url' => $url,
116
        ];
117
    }
118
119
    /**
120
     * @param HTTPResponse $response
121
     * @param string       $url
122
     * @return bool
123
     */
124
    protected function publishRedirect($response, $url)
125
    {
126
        $success = true;
127
        if ($path = $this->URLtoPath($url)) {
128
            $location = $response->getHeader('Location');
129
            if ($this->getFileExtension() === 'php') {
130
                $phpContent = $this->generatePHPCacheFile($response);
131
                $success = $this->saveToPath($phpContent, $path . '.php');
132
            }
133
            return $this->saveToPath($this->generateHTMLCacheRedirection($location), $path . '.html') && $success;
134
        }
135
        return false;
136
    }
137
138
    /**
139
     * @param HTTPResponse $response
140
     * @param string       $url
141
     * @return bool
142
     */
143
    protected function publishPage($response, $url)
144
    {
145
        $success = true;
146
        if ($path = $this->URLtoPath($url)) {
147
            if ($this->getFileExtension() === 'php') {
148
                $phpContent = $this->generatePHPCacheFile($response);
149
                $success = $this->saveToPath($phpContent, $path . '.php');
150
            }
151
            return $this->saveToPath($response->getBody(), $path . '.html') && $success;
152
        }
153
        return false;
154
    }
155
156
    /**
157
     * @param string $content
158
     * @param string $filePath
159
     * @return bool
160
     */
161
    protected function saveToPath($content, $filePath)
162
    {
163
        if (empty($content)) {
164
            return false;
165
        }
166
167
        // Write to a temporary file first
168
        $temporaryPath = tempnam(TEMP_PATH, 'filesystempublisher_');
169
        if (file_put_contents($temporaryPath, $content) === false) {
170
            return false;
171
        }
172
173
        // Move the temporary file to the desired location (prevents unlocked files from being read during write)
174
        $publishPath = $this->getDestPath() . DIRECTORY_SEPARATOR . $filePath;
175
        Filesystem::makeFolder(dirname($publishPath));
176
177
        return rename($temporaryPath, $publishPath);
178
    }
179
180
    protected function deleteFromPath($filePath)
181
    {
182
        $deletePath = $this->getDestPath() . DIRECTORY_SEPARATOR . $filePath;
183
        if (file_exists($deletePath)) {
184
            $success = unlink($deletePath);
185
        } else {
186
            $success = true;
187
        }
188
189
        return $success;
190
    }
191
192
    protected function URLtoPath($url)
193
    {
194
        return URLtoPath($url, BASE_URL, FilesystemPublisher::config()->get('domain_based_caching'));
195
    }
196
197
    protected function pathToURL($path)
198
    {
199
        if (strpos($path, $this->getDestPath()) === 0) {
200
            //Strip off the full path of the cache dir from the front
201
            $path = substr($path, strlen($this->getDestPath()));
202
        }
203
204
        // Strip off the file extension and leading /
205
        $relativeURL = substr($path, 0, (strrpos($path, ".")));
206
        $relativeURL = ltrim($relativeURL, '/');
207
208
        if (FilesystemPublisher::config()->get('domain_based_caching')) {
209
            // factor in the domain as the top dir
210
            return Director::protocol() . $relativeURL;
211
        }
212
213
        return $relativeURL == 'index' ? Director::absoluteBaseURL() : Director::absoluteURL($relativeURL);
214
    }
215
216
    public function getPublishedURLs($dir = null, &$result = [])
217
    {
218
        if ($dir == null) {
219
            $dir = $this->getDestPath();
220
        }
221
222
        $root = scandir($dir);
223
        foreach ($root as $fileOrDir) {
224
            if (strpos($fileOrDir, '.') === 0) {
225
                continue;
226
            }
227
            $fullPath = $dir . DIRECTORY_SEPARATOR . $fileOrDir;
228
            // we know html will always be generated, this prevents double ups
229
            if (is_file($fullPath) && pathinfo($fullPath)['extension'] == 'html') {
230
                $result[] = $this->pathToURL($fullPath);
231
                continue;
232
            }
233
234
            if (is_dir($fullPath)) {
235
                $this->getPublishedURLs($fullPath, $result);
236
            }
237
        }
238
        return $result;
239
    }
240
}
241