diff --git a/docs/en/basic_configuration.md b/docs/en/basic_configuration.md index 0bf0005f..6141f7ff 100644 --- a/docs/en/basic_configuration.md +++ b/docs/en/basic_configuration.md @@ -48,6 +48,18 @@ class MyFormPage extends Page } ``` +## Excluding response codes + +Default behaviour is that static files are generated for all page responses, regardless of the response's status code. +If you would like to exclude certain status codes from being statically cached, add them here + +```yaml +SilverStripe\StaticPublishQueue\Publisher\FilesystemPublisher: + disallowed_status_codes: + - 404 + - 500 +``` + ## Control when child/parent pages are regenerated in cache actions There are two configurations available, and they can both be set to one of three available values: diff --git a/src/Publisher/FilesystemPublisher.php b/src/Publisher/FilesystemPublisher.php index ca9084fd..0a34f9d7 100644 --- a/src/Publisher/FilesystemPublisher.php +++ b/src/Publisher/FilesystemPublisher.php @@ -12,6 +12,8 @@ class FilesystemPublisher extends Publisher { + private static array $disallowed_status_codes = []; + /** * @var string */ @@ -101,19 +103,32 @@ public function publishURL($url, $forcePublish = false) { if (!$url) { user_error('Bad url:' . var_export($url, true), E_USER_WARNING); + return; } + $success = false; $response = $this->generatePageResponse($url); $statusCode = $response->getStatusCode(); $doPublish = ($forcePublish && $this->getFileExtension() === 'php') || $statusCode < 400; + if (in_array($statusCode, static::config()->get('disallowed_status_codes'))) { + return [ + 'published' => false, + // Considering this a "success" since the behaviour is as expected + 'success' => true, + 'responsecode' => $statusCode, + 'url' => $url, + ]; + } + if ($statusCode >= 300 && $statusCode < 400) { // publish redirect response $success = $this->publishRedirect($response, $url); } elseif ($doPublish) { $success = $this->publishPage($response, $url); } + return [ 'published' => $doPublish, 'success' => $success, diff --git a/tests/php/Publisher/FilesystemPublisherTest.php b/tests/php/Publisher/FilesystemPublisherTest.php index 486b3b16..c902e29a 100644 --- a/tests/php/Publisher/FilesystemPublisherTest.php +++ b/tests/php/Publisher/FilesystemPublisherTest.php @@ -268,6 +268,17 @@ public function testErrorPageWhenPHP(): void $this->assertSame(404, $phpCacheConfig['responseCode']); } + public function testNoPublishOnDisallowedResponseCode(): void + { + $this->logOut(); + + Config::modify()->set(FilesystemPublisher::class, 'disallowed_status_codes', [404]); + + $this->fsp->publishURL('page_not_exists', true); + $this->assertFileDoesNotExist($this->fsp->getDestPath() . 'page_not_exists.html'); + $this->assertFileDoesNotExist($this->fsp->getDestPath() . 'page_not_exists.php'); + } + public function testRedirectorPageWhenPHP(): void { $redirectorPage = RedirectorPage::create();