diff --git a/.gitignore b/.gitignore index 71deb5c..40b1aa5 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /tests/assets/ +/.phpunit.result.cache diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 15f0f1e..0000000 --- a/.travis.yml +++ /dev/null @@ -1,58 +0,0 @@ -# See https://github.com/silverstripe-labs/silverstripe-travis-support for setup details and example of testing OPTIONAL modules - -language: php - -dist: trusty - -php: - - 5.6 - -env: - global: - - COMPOSER_ROOT_VERSION=5.0.x-dev - - SS_BASE_URL="https://localhost/" - -## Cache composer bits -cache: - directories: - - $HOME/.composer/cache/files - -matrix: - include: - - php: 5.6 - env: - - DB=MYSQL - - RECIPE_VERSION=1.0.x-dev - - PHPCS_TEST=1 - - php: 7.0 - env: - - DB=MYSQL - - RECIPE_VERSION=1.1.x-dev - # This doesn't work due to Multisites not being built to be compatible. - #- MULTISITES_VERSION=5.0.2 # NOTE: Test at a version we know definitely works. - - php: 7.1 - env: - - DB=MYSQL - - PHPSTAN_TEST=1 - - RECIPE_VERSION=1.2.x-dev - - php: 7.2 - env: - - DB=MYSQL - - PHPSTAN_TEST=1 - - RECIPE_VERSION=1.2.x-dev - # This doesn't work due to Multisites not being built to be compatible. - #- MULTISITES_VERSION=master # NOTE: Test against the tip for regressions. This could cause failures! - -before_script: - - phpenv rehash - - phpenv config-rm xdebug.ini - - composer validate - - composer require --no-update silverstripe/recipe-cms:$RECIPE_VERSION - - if [[ $MULTISITES_VERSION ]]; then composer require --no-update symbiote/silverstripe-multisites:5.0.2; fi - - if [[ $PHPSTAN_TEST ]]; then composer require phpstan/phpstan-shim:0.9.2; fi - - composer install --prefer-dist --no-interaction --no-progress --no-suggest --optimize-autoloader --verbose --profile - -script: - - if [[ $PHPCS_TEST ]]; then vendor/bin/phpcs src/ tests/ -n; fi - - if [[ $PHPSTAN_TEST ]]; then vendor/bin/phpstan analyse src/ -c "phpstan.neon" -a "tests/bootstrap-phpstan.php" --level 3; fi - - vendor/bin/phpunit diff --git a/LICENSE.md b/LICENSE.md index 4d8e728..ab31efd 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ BSD 3-Clause License -Copyright (c) 2017, Symbiote. +Copyright (c) 2024, Symbiote. All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/README.md b/README.md index 90d6332..74f7a7c 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,19 @@ # Old Man -[![Build Status](https://travis-ci.org/symbiote/silverstripe-oldman.svg?branch=master)](https://travis-ci.org/symbiote/silverstripe-oldman) -[![Latest Stable Version](https://poser.pugx.org/symbiote/silverstripe-oldman/version.svg)](https://github.com/symbiote/silverstripe-oldman/releases) -[![Latest Unstable Version](https://poser.pugx.org/symbiote/silverstripe-oldman/v/unstable.svg)](https://packagist.org/packages/symbiote/silverstripe-oldman) -[![Total Downloads](https://poser.pugx.org/symbiote/silverstripe-oldman/downloads.svg)](https://packagist.org/packages/symbiote/silverstripe-oldman) -[![License](https://poser.pugx.org/symbiote/silverstripe-oldman/license.svg)](https://github.com/symbiote/silverstripe-oldman/blob/master/LICENSE.md) - A module to aid in the purging of Cloudflare caches. ![oldman-cloud](https://user-images.githubusercontent.com/3859574/31596225-d2213356-b28c-11e7-97c3-e73500083c34.png) ## Composer Install -**[SilverStripe 3.X](https://github.com/symbiote/silverstripe-oldman/tree/1)** -``` -composer require symbiote/silverstripe-oldman:~1.0 -``` - -**[SilverStripe 4.X](https://github.com/symbiote/silverstripe-oldman/tree/master)** ``` -composer require symbiote/silverstripe-oldman:~3.0 +composer require symbiote/silverstripe-oldman:^4 ``` ## Requirements -* PHP 5.4+ -* SilverStripe 3.2+ +* PHP 7.4+ +* Silverstripe 4+ | 5+ ## Documentation @@ -38,3 +26,4 @@ composer require symbiote/silverstripe-oldman:~3.0 * [Steadlane Cloudflare](https://github.com/steadlane/silverstripe-cloudflare) for being the basis for this module * [James Bell](https://github.com/jamesryanbell/cloudflare) for his Cloudflare Library +* [UndefinedOffset](https://github.com/webbuilders-group/silverstripe-oldman) for the SS 5 upgrade and adaptation for the official Cloudflare API diff --git a/_config/config.yml b/_config/config.yml index a5f1733..6b79a4b 100644 --- a/_config/config.yml +++ b/_config/config.yml @@ -4,3 +4,7 @@ Name: cloudflare_extensions SilverStripe\CMS\Model\SiteTree: extensions: - Symbiote\Cloudflare\SiteTreeExtension + +SilverStripe\Assets\File: + extensions: + - Symbiote\Cloudflare\FileExtension diff --git a/composer.json b/composer.json index c2dfb9d..7e8939e 100644 --- a/composer.json +++ b/composer.json @@ -17,13 +17,13 @@ } ], "require": { - "php": ">=5.6", - "silverstripe/cms": "^4.0", - "jamesryanbell/cloudflare": "~1.11" + "php": ">=8.1", + "silverstripe/cms": "^4|^5", + "cloudflare/sdk": "~1.3" }, "require-dev": { "squizlabs/php_codesniffer": "^3.0", - "phpunit/phpunit": "^5.7" + "phpunit/phpunit": "^9.5" }, "scripts": { "phpcbf": "phpcbf -n src/ tests/" @@ -33,12 +33,6 @@ "Symbiote\\Cloudflare\\": "src/", "Symbiote\\Cloudflare\\Tests\\": "tests/" } - }, - "extra": { - "branch-alias": { - "dev-master": "3.0.x-dev" - }, - "installer-name": "oldman" }, "replace": { "silbinarywolf/silverstripe-oldman": "self.version" diff --git a/docs/en/quick-start.md b/docs/en/quick-start.md index 83fe016..4dafebb 100644 --- a/docs/en/quick-start.md +++ b/docs/en/quick-start.md @@ -4,6 +4,14 @@ 2. Configure in YML, example below: ```yml +Symbiote\Cloudflare\Cloudflare: + enabled: true + api_token: '24ca61e15fb2aa62a31-212a90f2674f_3451f8' # Needs the the "Cache Purge" permission: + zone_id: '73a40b2c0c10f468cb658f67b9d46fff' +``` + +Alternatively you can use you Global API Key: +```yml Symbiote\Cloudflare\Cloudflare: enabled: true email: 'silverstripe@gmail.com' @@ -11,6 +19,16 @@ Symbiote\Cloudflare\Cloudflare: zone_id: '73a40b2c0c10f468cb658f67b9d46fff' ``` +Note the `email`, `auth_key`, `zone_id`, and `api_token` yaml options can also be represented with service properties so you can store this information in the environment file. For example: + +```yml +Symbiote\Cloudflare\Cloudflare: + enabled: true + api_token: "`CLOUDFLARE_API_TOKEN`" + zone_id: "`CLOUDFLARE_ZONE_ID`" +``` + + 3. Publishing / unpublishing a page from the CMS will now clear the Cloudflare cache for that URL. 4. For clearing CSS, JavaScript and images from the Cloudflare cache, see the [Advanced Usage](advanced-usage.md) section. diff --git a/phpunit.xml.dist b/phpunit.xml.dist index b543ea6..e398543 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,13 +1,14 @@ - - - tests/ - - - - src/ - - tests/ - - - + + + + + src/ + + + tests/ + + + + tests/ + diff --git a/src/Cloudflare.php b/src/Cloudflare.php index 48f5d48..ea3dbc8 100644 --- a/src/Cloudflare.php +++ b/src/Cloudflare.php @@ -2,19 +2,21 @@ namespace Symbiote\Cloudflare; -use Exception; -use Symbiote\Multisites\Model\Site; -use Cloudflare\Api; -use Cloudflare\Zone\Cache; -use SilverStripe\Core\Injector\Injector; -use SilverStripe\CMS\Model\SiteTree; +use Cloudflare\API\Adapter\Guzzle as Cloudflare_Guzzle; +use Cloudflare\API\Auth\APIKey as Cloudflare_APIKey; +use Cloudflare\API\Auth\APIToken as Cloudflare_APIToken; +use Cloudflare\API\Endpoints\Zones as Cloudflare_Zones; use SilverStripe\Assets\File; -use SilverStripe\Control\Director; +use SilverStripe\CMS\Model\SiteTree; use SilverStripe\Control\Controller; -use SilverStripe\View\Requirements; +use SilverStripe\Control\Director; +use SilverStripe\Core\Config\Configurable; use SilverStripe\Core\Extensible; use SilverStripe\Core\Injector\Injectable; -use SilverStripe\Core\Config\Configurable; +use SilverStripe\Core\Injector\Injector; +use SilverStripe\View\Requirements; +use Symbiote\Multisites\Model\Site; +use Exception; class Cloudflare { @@ -23,9 +25,9 @@ class Cloudflare use Configurable; /** - * Cloudflare can only purge 500 files per request. + * Cloudflare can only purge 30 files per request. */ - const MAX_PURGE_FILES_PER_REQUEST = 500; + public const MAX_PURGE_FILES_PER_REQUEST = 30; /** * String representation of this class. @@ -33,7 +35,7 @@ class Cloudflare * * @var string */ - const CLOUDFLARE_CLASS = 'Symbiote\Cloudflare\Cloudflare'; + public const CLOUDFLARE_CLASS = 'Symbiote\Cloudflare\Cloudflare'; /** * String representation of the "Filesystem" class. @@ -41,7 +43,7 @@ class Cloudflare * * @var string */ - const FILESYSTEM_CLASS = 'Symbiote\Cloudflare\Filesystem'; + public const FILESYSTEM_CLASS = 'Symbiote\Cloudflare\Filesystem'; /** * String representation of a Multisite "Site" DataObject class. @@ -49,7 +51,7 @@ class Cloudflare * * @var string */ - const SITE_CLASS = 'Symbiote\Multisites\Model\Site'; + public const SITE_CLASS = 'Symbiote\Multisites\Model\Site'; /** * @var boolean @@ -73,6 +75,16 @@ class Cloudflare */ private static $auth_key = ''; + /** + * API Token + * + * eg. 24ca61e15fb2aa62a312-12a90f2674f_3451f8 + * + * @var string + * @config + */ + private static $api_token = ''; + /** * Zone ID * @@ -102,13 +114,10 @@ class Cloudflare * * @var array */ - private static $image_file_extensions = array( - 'svg', - 'webp', - ); + private static $image_file_extensions = ['svg', 'webp']; /** - * @var \Cloudflare\Api + * @var Cloudflare_Zones */ protected $client; @@ -121,7 +130,24 @@ public function __construct() { $this->filesystem = Injector::inst()->get(self::FILESYSTEM_CLASS); if ($this->config()->enabled) { - $this->client = new Api($this->config()->email, $this->config()->auth_key); + if ($this->config()->api_token) { + $this->client = new Cloudflare_Zones( + new Cloudflare_Guzzle( + new Cloudflare_APIToken( + Injector::inst()->convertServiceProperty($this->config()->api_token) + ), + ) + ); + } else { + $this->client = new Cloudflare_Zones( + new Cloudflare_Guzzle( + new Cloudflare_APIKey( + Injector::inst()->convertServiceProperty($this->config()->email), + Injector::inst()->convertServiceProperty($this->config()->auth_key) + ), + ) + ); + } } } @@ -145,10 +171,13 @@ public function purgeAll() if (!$this->client) { return null; } - $cache = new Cache($this->client); - $response = $cache->purge($this->getZoneIdentifier(), true); - $result = new CloudflareResult(array(), $response->errors); - return $result; + + try { + $this->client->cachePurgeEverything($this->getZoneIdentifier()); + return new CloudflareResult([], []); + } catch (Exception $e) { + return new CloudflareResult([], [$e->getMessage()]); + } } /** @@ -176,11 +205,11 @@ public function purgeImages() public function purgeCSSAndJavascript() { return $this->purgeFilesByExtensions( - array( + [ 'css', 'js', 'json', - ) + ] ); } @@ -198,10 +227,10 @@ public function purgeURLs(array $absoluteOrRelativeURLList) } // Process list of relative/absolute URLs - $urlsToPurge = array(); + $urlsToPurge = []; foreach ($absoluteOrRelativeURLList as $absoluteOrRelativeURL) { - $isAbsoluteURL = strpos($absoluteOrRelativeURL, 'http://') !== false || - strpos($absoluteOrRelativeURL, 'https://') !== false; + $isAbsoluteURL = str_contains((string) $absoluteOrRelativeURL, 'http://') || + str_contains((string) $absoluteOrRelativeURL, 'https://'); // Convert to absolute URL if (!$isAbsoluteURL) { @@ -219,7 +248,7 @@ public function purgeURLs(array $absoluteOrRelativeURLList) */ public function getZoneIdentifier() { - return $this->config()->zone_id; + return Injector::inst()->convertServiceProperty($this->config()->zone_id); } /** @@ -230,20 +259,20 @@ protected function purgeFilesByExtensions(array $fileExtensions) if (!$this->client) { return null; } + $files = $this->getFilesToPurgeByExtensions($fileExtensions, false); // Purge files - $cache = new Cache($this->client); $zoneIdentifier = $this->getZoneIdentifier(); - $errors = array(); + $errors = []; foreach (array_chunk($files, self::MAX_PURGE_FILES_PER_REQUEST) as $filesChunk) { - $response = $cache->purge_files($zoneIdentifier, $filesChunk); - if (!$response->success) { - $errors = array_merge($errors, $response->errors); + try { + $this->client->cachePurge($zoneIdentifier, $filesChunk); + } catch (Exception $e) { + $errors[] = $e->getMessage(); } } - // $result = new CloudflareResult($files, $errors); return $result; } @@ -265,7 +294,7 @@ protected function isHomePage(SiteTree $page) */ private function getLinksToPurgeByPage(SiteTree $page) { - $files = array(); + $files = []; // Use alternate base url if defined for cache clearing $baseURL = $this->config()->base_url; $pageLink = ''; @@ -305,27 +334,25 @@ private function getLinksToPurgeByPage(SiteTree $page) private function getFilesToPurgeByExtensions(array $fileExtensions, $ignoreDatabaseRecords) { // Scan files in the project directory to purge - $folderList = array( + $folderList = [ // Get all files built by `Requirements` system (*.css, *.js) - Director::baseFolder().'/'.ASSETS_DIR.'/'.Requirements::backend()->getCombinedFilesFolder(), + Director::baseFolder() . '/' . (defined('PUBLIC_DIR') ? PUBLIC_DIR . '/' : '') . ASSETS_DIR . '/' . Requirements::backend()->getCombinedFilesFolder(), // Get all module / theme files - Director::baseFolder() - ); - $files = array(); + Director::baseFolder(), + ]; + $files = []; foreach ($folderList as $folder) { $files = array_merge($files, $this->filesystem->getFilesWithExtensionsRecursively($folder, $fileExtensions)); } // Get all files in database and purge (not using local scan for /assets/ so we can support remotely hosted files in S3/etc) if (!$ignoreDatabaseRecords) { - $fileExtensionsPrefixedWithDot = array(); + $fileExtensionsPrefixedWithDot = []; foreach ($fileExtensions as $fileExtension) { $fileExtensionsPrefixedWithDot[] = '.'.$fileExtension; } $fileRecordList = File::get()->filter( - array( - 'Filename:EndsWith' => $fileExtensionsPrefixedWithDot - ) + ['FileFilename:EndsWith' => $fileExtensionsPrefixedWithDot] ); $files = array_merge($files, $fileRecordList->map('ID', 'Link')->toArray()); } @@ -338,21 +365,15 @@ private function getFilesToPurgeByExtensions(array $fileExtensions, $ignoreDatab */ private function purgeFiles(array $filesToPurge) { - $cache = new Cache($this->client); - $response = $cache->purge_files($this->getZoneIdentifier(), $filesToPurge); $errors = []; - if (!$response->success) { - if (isset($response->errors)) { - $errors = $response->errors; - } else { - throw new \Exception($response->error); - //if (isset($response->error)) { - // $error = new \stdClass; - // $error->message = $response->error; - // $errors[] = $error; - //} - } + try { + $this->client->cachePurge($this->getZoneIdentifier(), $filesToPurge); + } catch (Exception $e) { + $errors[] = $e->getMessage(); + + throw $e; } + $result = new CloudflareResult($filesToPurge, $errors); return $result; } diff --git a/src/CloudflareResult.php b/src/CloudflareResult.php index 7419f73..3493404 100644 --- a/src/CloudflareResult.php +++ b/src/CloudflareResult.php @@ -7,33 +7,20 @@ class CloudflareResult /** * @var array */ - protected $successes = array(); + protected $successes = []; /** * @var array */ - protected $errors = array(); + protected $errors = []; public function __construct(array $files, array $errorRecords) { - // Determine what purged files were un-successful. - $purgedFiles = $files; - foreach ($errorRecords as $errorRecord) { - foreach ($purgedFiles as $key => $url) { - if (strpos($errorRecord->message, $url) !== false) { - unset($purgedFiles[$key]); - } - } - } - // Apply to this object - $this->successes = $purgedFiles; - if ($errorRecords) { - $this->errors = array(); - foreach ($errorRecords as $errorRecord) { - $this->errors[] = $errorRecord->message; - } + if (empty($errorRecords)) { + $this->successes = $files; } + $this->errors = $errorRecords; } /** diff --git a/src/Filesystem.php b/src/Filesystem.php index 9931fb3..f0fec7b 100644 --- a/src/Filesystem.php +++ b/src/Filesystem.php @@ -14,16 +14,18 @@ class Filesystem * @config * @var array */ - private static $blacklist_filenames = array( + private static $blacklist_filenames = [ '.', '..', '.git', '.svn', '.hg', - 'composer.json', // ignore Composer - 'package.json', // ignore NPM/Yarn - 'node_modules', // very large folder on local dev machines - ); + 'composer.json', + // ignore Composer + 'package.json', + // ignore NPM/Yarn + 'node_modules', + ]; /** * Ban certain directories from being traversed to increase purge response time. @@ -31,8 +33,7 @@ class Filesystem * @config * @var array */ - private static $blacklist_absolute_pathnames = array( - ); + private static $blacklist_absolute_pathnames = []; /** * @config @@ -47,13 +48,7 @@ class Filesystem * * @var array */ - protected $defaultBlacklistAbsolutePathnames = array( - '%BASE_FOLDER%/framework', - '%BASE_FOLDER%/cms', - '%BASE_FOLDER%/assets', - '%BASE_FOLDER%/vendor', - '%BASE_FOLDER%/silverstripe-cache', - ); + protected $defaultBlacklistAbsolutePathnames = ['%BASE_FOLDER%/framework', '%BASE_FOLDER%/cms', '%BASE_FOLDER%/assets', '%BASE_FOLDER%/vendor', '%BASE_FOLDER%/silverstripe-cache']; /** * Walk the directory provided recursively and get all files that match @@ -63,14 +58,14 @@ class Filesystem */ public function getFilesWithExtensionsRecursively($directory, array $extensionsToMatch) { - $directory_stack = array($directory); + $directory_stack = [$directory]; - $ignored_filename_list = Config::inst()->get(__CLASS__, 'blacklist_filenames'); - $ignored_pathname_list = array(); - if (!Config::inst()->get(__CLASS__, 'disable_default_blacklist_absolute_pathnames')) { + $ignored_filename_list = Config::inst()->get(self::class, 'blacklist_filenames'); + $ignored_pathname_list = []; + if (!Config::inst()->get(self::class, 'disable_default_blacklist_absolute_pathnames')) { $ignored_pathname_list = $this->defaultBlacklistAbsolutePathnames; } - $custom_ignored_pathname_list = Config::inst()->get(__CLASS__, 'blacklist_absolute_pathnames'); + $custom_ignored_pathname_list = Config::inst()->get(self::class, 'blacklist_absolute_pathnames'); if ($custom_ignored_pathname_list) { $ignored_pathname_list = array_merge($ignored_pathname_list, $custom_ignored_pathname_list); } @@ -81,25 +76,25 @@ public function getFilesWithExtensionsRecursively($directory, array $extensionsT if (!$base_url) { $base_url = Director::absoluteURL('/'); } - $base_url = rtrim($base_url, '/'); + $base_url = rtrim((string) $base_url, '/'); // Convert from flat arrays to lookup for speed - $ignored_filename_lookup = array(); + $ignored_filename_lookup = []; if ($ignored_filename_list) { foreach ($ignored_filename_list as $ignored_filename) { $ignored_filename_lookup[$ignored_filename] = true; } } - $ignored_pathname_lookup = array(); + $ignored_pathname_lookup = []; if ($ignored_pathname_list) { foreach ($ignored_pathname_list as $ignored_pathname) { - $ignored_pathname = str_replace(array('%BASE_FOLDER%', '\\'), array($base_folder, '/'), $ignored_pathname); + $ignored_pathname = str_replace(['%BASE_FOLDER%', '\\'], [$base_folder, '/'], $ignored_pathname); $ignored_pathname_lookup[$ignored_pathname] = true; } } // Get all files - $result_file_list = array(); + $result_file_list = []; while ($directory_stack) { $current_directory = array_shift($directory_stack); $current_directory = str_replace('\\', '/', $current_directory); @@ -135,7 +130,7 @@ public function getFilesWithExtensionsRecursively($directory, array $extensionsT // ie. "/shared/httpd/{project-folder}/htdocs/betterbuttons/css/betterbuttons_nested_form.css" // to: "http://{project-folder}.symlocal/betterbuttons/css/betterbuttons_nested_form.css" // - $pathname = str_replace(array($base_folder), array($base_url), $pathname); + $pathname = str_replace([$base_folder], [$base_url], $pathname); $result_file_list[] = $pathname; } diff --git a/src/PurgeTask.php b/src/PurgeTask.php index 16002b8..67b7e46 100644 --- a/src/PurgeTask.php +++ b/src/PurgeTask.php @@ -2,10 +2,8 @@ namespace Symbiote\Cloudflare; -use Psr\Log\LoggerInterface; -use SilverStripe\Core\Injector\Injector; use SilverStripe\Control\Director; -use SilverStripe\Dev\BuildTask; +use SilverStripe\Core\Injector\Injector; // // NOTE(Jake): 2018-04-26 @@ -42,17 +40,6 @@ public function endRun($request) $result = $this->callPurgeFunction($client); $timeTakenInSeconds = number_format(microtime(true) - $startTime, 2, '.', ''); - // Show output - $status = 'PURGE SUCCESS'; - - $successes = $result->getSuccesses(); - if ($successes) { - $this->log('Successes:'); - foreach ($successes as $success) { - $this->log($success); - } - } - $errors = $result->getErrors(); if ($errors) { @@ -69,10 +56,10 @@ public function endRun($request) // If no successes or errors, assume success. // ie. this is for purge everything. echo Director::is_cli() ? "\n" : '
'; - if (!$successes && !$errors) { - $this->log($status.'.'); + if (!$errors) { + $this->log('SUCCESS'); } else { - $this->log($status.'. ('.count($successes).' successes, '.count($errors).' failed)'); + $this->log($status.'. ('.count($errors).' failed)'); } $this->log('Time taken: '.$timeTakenInSeconds.' seconds.'); } diff --git a/src/PurgeURLTask.php b/src/PurgeURLTask.php index 8dae0ef..57ef87e 100644 --- a/src/PurgeURLTask.php +++ b/src/PurgeURLTask.php @@ -10,7 +10,7 @@ class PurgeURLTask extends \SilverStripe\Dev\BuildTask protected $description = 'Purges a single or multiple URLs, with an absolute or relative URL (ie. url="admin/,Security/" or url="http://myproductionsite.com/admin, http://myproductionsite.com/Security")'; - protected $param_url = array(); + protected $param_url = []; public function run($request) { @@ -21,7 +21,7 @@ public function run($request) } // Allow multiple URLs - $urlList = explode(',', $url); + $urlList = explode(',', (string) $url); foreach ($urlList as $i => $url) { $url = trim($url); // Remove URL if it's a blank string, this allows trailing commas diff --git a/tests/CloudflarePurgeFileTest.php b/tests/CloudflarePurgeFileTest.php index 8ad959d..e9ff12b 100644 --- a/tests/CloudflarePurgeFileTest.php +++ b/tests/CloudflarePurgeFileTest.php @@ -2,27 +2,25 @@ namespace Symbiote\Cloudflare\Tests; -use ReflectionObject; -use SilverStripe\CMS\Model\SiteTree; -use SilverStripe\Core\Injector\Injector; -use SilverStripe\View\Requirements; use SilverStripe\Core\Config\Config; +use SilverStripe\Core\Injector\Injector; use SilverStripe\Dev\FunctionalTest; +use SilverStripe\View\Requirements; use Symbiote\Cloudflare\Cloudflare; -use Symbiote\Cloudflare\Filesystem; +use ReflectionObject; class CloudflarePurgeFileTest extends FunctionalTest { /** * The assets used by the tests */ - const ASSETS_DIR = 'vendor/symbiote/silverstripe-oldman/tests/assets'; + public const ASSETS_DIR = 'vendor/symbiote/silverstripe-oldman/tests/assets'; /** * This is used to determine if the 'framework' folder was scanned * for CSS/JS files. */ - const FRAMEWORK_CSS_FILE = 'vendor/silverstripe/framework/src/Dev/Install/client/styles/install.css'; + public const FRAMEWORK_CSS_FILE = 'vendor/silverstripe/framework/client/styles/debug.css'; protected static $disable_themes = true; @@ -45,22 +43,15 @@ public function testPurgeCSSAndJS() Requirements::set_combined_files_enabled(true); // not enabled by default in SS4 Requirements::combine_files( 'combined.min.css', - array( - self::ASSETS_DIR.'/test_combined_css_a.css', - self::ASSETS_DIR.'/test_combined_css_b.css', - ) + [self::ASSETS_DIR.'/test_combined_css_a.css', self::ASSETS_DIR.'/test_combined_css_b.css'] ); Requirements::process_combined_files(); // $files = $this->getFilesToPurgeByExtensions( - array( - 'css', - 'js', - 'json', - ) + ['css', 'js', 'json'] ); - $expectedFiles = array( + $expectedFiles = [ // NOTE(Jake): 2018-04-19 // // In SS4, combined files have a partial-hash @@ -69,15 +60,12 @@ public function testPurgeCSSAndJS() // So we only partially match the name. // ASSETS_DIR.'/_combinedfiles/combined.min-', - // NOTE(Jake): 2018-04-19, Moved under "vendor" in SS4. - //'oldman/tests/assets/test_combined_css_a.css', - //'oldman/tests/assets/test_combined_css_b.css', - ); + ]; // Search for matches $matchCount = 0; foreach ($files as $file) { foreach ($expectedFiles as $expectedFile) { - if (strpos($file, $expectedFile) !== false) { + if (str_contains((string) $file, $expectedFile)) { $matchCount++; break; } @@ -92,7 +80,7 @@ public function testPurgeCSSAndJS() // If it has a file from the 'framework' module, fail this test as it should be ignored. $hasFramework = false; foreach ($files as $file) { - $hasFramework = $hasFramework || (strpos($file, self::FRAMEWORK_CSS_FILE) !== false); + $hasFramework = $hasFramework || (str_contains((string) $file, self::FRAMEWORK_CSS_FILE)); } $this->assertFalse($hasFramework, 'Expected to specifically not get the "framework" file: '.self::FRAMEWORK_CSS_FILE); @@ -105,20 +93,16 @@ public function testPurgeCSSAndJS() */ public function testAllowBlacklistedDirectories() { - Config::inst()->update(Cloudflare::FILESYSTEM_CLASS, 'disable_default_blacklist_absolute_pathnames', true); + Config::inst()->set(Cloudflare::FILESYSTEM_CLASS, 'disable_default_blacklist_absolute_pathnames', true); $files = $this->getFilesToPurgeByExtensions( - array( - 'css', - 'js', - 'json', - ) + ['css', 'js', 'json'] ); - Config::inst()->update(Cloudflare::FILESYSTEM_CLASS, 'disable_default_blacklist_absolute_pathnames', false); + Config::inst()->set(Cloudflare::FILESYSTEM_CLASS, 'disable_default_blacklist_absolute_pathnames', false); // If it has a file from the 'framework' module, fail this test as it should be ignored. $hasFramework = false; foreach ($files as $file) { - $hasFramework = $hasFramework || (strpos($file, self::FRAMEWORK_CSS_FILE) !== false); + $hasFramework = $hasFramework || (str_contains((string) $file, self::FRAMEWORK_CSS_FILE)); } $this->assertTrue( $hasFramework, diff --git a/tests/CloudflarePurgePageTest.php b/tests/CloudflarePurgePageTest.php index 4949054..5038239 100644 --- a/tests/CloudflarePurgePageTest.php +++ b/tests/CloudflarePurgePageTest.php @@ -2,15 +2,14 @@ namespace Symbiote\Cloudflare\Tests; -use ReflectionObject; -use SilverStripe\Core\Injector\Injector; -use SilverStripe\Control\Director; +use Cloudflare\API\Endpoints\EndpointException; +use SilverStripe\CMS\Controllers\RootURLController; use SilverStripe\CMS\Model\SiteTree; use SilverStripe\Core\Config\Config; +use SilverStripe\Core\Injector\Injector; use SilverStripe\Dev\FunctionalTest; use Symbiote\Cloudflare\Cloudflare; -use SilverStripe\CMS\Controllers\RootURLController; -use SilverStripe\Control\Controller; +use ReflectionObject; //use Symbiote\Multisites\Model\Site; @@ -18,7 +17,7 @@ class CloudflarePurgePageTest extends FunctionalTest { protected static $disable_themes = true; - public function setUp() + public function setUp(): void { parent::setUp(); if (!defined('SS_BASE_URL')) { @@ -46,16 +45,12 @@ public function testPurgeHomePage() $record->write(); $record->publishSingle(); - $homePage = SiteTree::get()->filter(array('URLSegment' => $homeSlug))->first(); + $homePage = SiteTree::get()->filter(['URLSegment' => $homeSlug])->first(); $linksBeingCleared = $this->getLinksToPurgeByPage($homePage); $baseUrl = rtrim(SS_BASE_URL, '/'); $this->assertEquals( - array( - '', - $baseUrl, - $baseUrl.'/', - ), + ['', $baseUrl, $baseUrl.'/'], $linksBeingCleared, 'Expected "Cloudflare::purgePage" on a home page record to return both the base url and /' ); @@ -74,15 +69,12 @@ public function testPurgeRandomPage() $record->write(); $record->publishSingle(); - $record = SiteTree::get()->filter(array('URLSegment' => 'cloudflare-test-page'))->first(); + $record = SiteTree::get()->filter(['URLSegment' => 'cloudflare-test-page'])->first(); $linksBeingCleared = $this->getLinksToPurgeByPage($record); $baseUrl = rtrim(SS_BASE_URL, '/'); $this->assertEquals( - array( - $baseUrl.'/cloudflare-test-page', - $baseUrl.'/cloudflare-test-page/', - ), + [$baseUrl.'/cloudflare-test-page', $baseUrl.'/cloudflare-test-page/'], $linksBeingCleared, 'Expected "Cloudflare::purgePage" on a home page record to return both the base url and /' ); @@ -96,14 +88,14 @@ public function testPurgeRandomPage() */ public function testPurgePage() { - Config::inst()->update(Cloudflare::class, 'enabled', true); + Config::inst()->set(Cloudflare::class, 'enabled', true); $wasPurgePageCalled = false; $record = SiteTree::create(); $record->write(); try { $record->publishSingle(); - } catch (\Cloudflare\Exception\AuthenticationException $e) { + } catch (EndpointException) { // NOTE(Jake): 2018-04-26 // // This is expected behaviour. Since we're running `purgePage` with Cloudflare diff --git a/tests/bootstrap-phpstan.php b/tests/bootstrap-phpstan.php index 9a03d36..1129540 100644 --- a/tests/bootstrap-phpstan.php +++ b/tests/bootstrap-phpstan.php @@ -1,6 +1,6 @@