Passed
Pull Request — master (#118)
by Daniel
02:09
created

FilesystemPublisher::setFileExtension()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 10
nc 2
nop 1
dl 0
loc 15
rs 9.9332
c 1
b 0
f 0
1
<?php
2
3
namespace SilverStripe\StaticPublishQueue\Publisher;
4
5
use SilverStripe\Assets\Filesystem;
6
use SilverStripe\Control\HTTPResponse;
7
use function SilverStripe\StaticPublishQueue\PathToURL;
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'], true)) {
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
     * @param bool $forcePublish
89
     * @return array A result array
90
     */
91
    public function publishURL($url, $forcePublish = false)
92
    {
93
        if (!$url) {
94
            user_error('Bad url:' . var_export($url, true), E_USER_WARNING);
95
            return;
96
        }
97
        $success = false;
98
        $response = $this->generatePageResponse($url);
99
        $statusCode = $response->getStatusCode();
100
        $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...
101
102
        if ($statusCode >= 300 && $statusCode < 400) {
103
            // publish redirect response
104
            $success = $this->publishRedirect($response, $url);
105
        } elseif ($doPublish) {
106
            $success = $this->publishPage($response, $url);
107
        }
108
        return [
109
            'published' => $doPublish,
110
            'success' => $success,
111
            'responsecode' => $statusCode,
112
            'url' => $url,
113
        ];
114
    }
115
116
    /**
117
     * @param HTTPResponse $response
118
     * @param string       $url
119
     * @return bool
120
     */
121
    protected function publishRedirect($response, $url)
122
    {
123
        $success = true;
124
        if ($path = $this->URLtoPath($url)) {
125
            $location = $response->getHeader('Location');
126
            if ($this->getFileExtension() === 'php') {
127
                $phpContent = $this->generatePHPCacheFile($response);
128
                $success = $this->saveToPath($phpContent, $path . '.php');
129
            }
130
            return $this->saveToPath($this->generateHTMLCacheRedirection($location), $path . '.html') && $success;
131
        }
132
        return false;
133
    }
134
135
    /**
136
     * @param HTTPResponse $response
137
     * @param string       $url
138
     * @return bool
139
     */
140
    protected function publishPage($response, $url)
141
    {
142
        $success = true;
143
        if ($path = $this->URLtoPath($url)) {
144
            if ($this->getFileExtension() === 'php') {
145
                $phpContent = $this->generatePHPCacheFile($response);
146
                $success = $this->saveToPath($phpContent, $path . '.php');
147
            }
148
            return $this->saveToPath($response->getBody(), $path . '.html') && $success;
149
        }
150
        return false;
151
    }
152
153
    /**
154
     * returns true on success and false on failure
155
     *
156
     * @param string $content
157
     * @param string $filePath
158
     * @return bool
159
     */
160
    protected function saveToPath($content, $filePath)
161
    {
162
        if (empty($content)) {
163
            return false;
164
        }
165
166
        // Write to a temporary file first
167
        $temporaryPath = tempnam(TEMP_PATH, 'filesystempublisher_');
168
        if (file_put_contents($temporaryPath, $content) === false) {
169
            return false;
170
        }
171
172
        // Move the temporary file to the desired location (prevents unlocked files from being read during write)
173
        $publishPath = $this->getDestPath() . DIRECTORY_SEPARATOR . $filePath;
174
        Filesystem::makeFolder(dirname($publishPath));
175
176
        $successWithPublish = rename($temporaryPath, $publishPath);
177
        if ($successWithPublish) {
178
            if (FilesystemPublisher::config()->get('use_gzip_compression')) {
179
                $publishPath = $this->compressFile($publishPath);
180
            }
181
        }
182
        return file_exists($publishPath);
183
    }
184
185
    /**
186
     * Compress the html file and store it gzipped
187
     *
188
     * @param string $publishPath
189
     * @return string The path of the compressed file
190
     */
191
    protected function compressFile($publishPath)
192
    {
193
        $data = file_get_contents($publishPath);
194
        $gzData = gzencode($data, 9);
195
        $gzPublishPath = $publishPath . '.gz';
196
        unlink($gzPublishPath);
197
        file_put_contents($gzPublishPath, $gzData);
198
        return $gzPublishPath;
199
    }
200
201
    protected function deleteFromPath($filePath)
202
    {
203
        $deletePath = $this->getDestPath() . DIRECTORY_SEPARATOR . $filePath;
204
        if (file_exists($deletePath)) {
205
            $success = unlink($deletePath);
206
        } else {
207
            $success = true;
208
        }
209
        if (file_exists($deletePath . '.gz')) {
210
            $success = unlink($deletePath . '.gz') && $success;
211
        }
212
213
        return $success;
214
    }
215
216
    protected function URLtoPath($url)
217
    {
218
        return URLtoPath($url, BASE_URL, FilesystemPublisher::config()->get('domain_based_caching'));
219
    }
220
221
    protected function pathToURL($path)
222
    {
223
        return PathToURL($path, $this->getDestPath(), FilesystemPublisher::config()->get('domain_based_caching'));
224
    }
225
226
    public function getPublishedURLs($dir = null, &$result = [])
227
    {
228
        if ($dir === null) {
229
            $dir = $this->getDestPath();
230
        }
231
232
        $root = scandir($dir);
233
        foreach ($root as $fileOrDir) {
234
            if (strpos($fileOrDir, '.') === 0) {
235
                continue;
236
            }
237
            $fullPath = $dir . DIRECTORY_SEPARATOR . $fileOrDir;
238
            // we know html will always be generated, this prevents double ups
239
            if (is_file($fullPath) && pathinfo($fullPath, PATHINFO_EXTENSION) === 'html') {
240
                $result[] = $this->pathToURL($fullPath);
241
                continue;
242
            }
243
244
            if (is_dir($fullPath)) {
245
                $this->getPublishedURLs($fullPath, $result);
246
            }
247
        }
248
        return $result;
249
    }
250
}
251