Completed
Push — master ( 9a0898...f1978f )
by Daniel
26s queued 12s
created

FilesystemPublisher::purgeAll()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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