From 254ed4801f7f185825aff27d99ef2d87d3df1c3e Mon Sep 17 00:00:00 2001 From: Robbie Averill Date: Thu, 5 Jan 2017 11:16:12 +1300 Subject: [PATCH] SilverStripe 4.x compatibility (#38) * Update composer constraint for 4.x compat * 4.x compatibility: Rename "code" to "src" and add PSR-4 autoloading * Restructure code and tests for PSR-4 * Implement namespaces * Implement namespaced throughout * PSR-2 formatting updates, separate Result from CheckSuite, implement PSR-3 logging, fix tests * FIX Routes and template location * Update readme. Allow check classes to be namespaced or not. * Add entry to changelog * FIX Ensure DatabaseCheckTest always has a member. Allow strings or objects for $check in the suite * Update readme to be clearer about passing checks with or without namespaces * Revert namespace checking and implement Injector aliases instead. Update readme. --- .scrutinizer.yml | 2 +- .travis.yml | 20 +-- .upgrade.yml | 29 ++++ _config.php | 2 + _config/injector.yml | 24 +++ _config/routes.yml | 10 +- changelog.md | 7 + composer.json | 61 ++++---- readme.md | 138 +++++++++++------- {code/checks => src/Checks}/DatabaseCheck.php | 21 ++- .../Checks}/ExternalURLCheck.php | 18 ++- .../FileAccessibilityAndValidationCheck.php | 38 +++-- {code/checks => src/Checks}/FileAgeCheck.php | 56 ++++--- .../Checks}/FileWriteableCheck.php | 28 ++-- {code/checks => src/Checks}/HasClassCheck.php | 11 +- .../Checks}/HasFunctionCheck.php | 13 +- .../Checks}/SMTPConnectCheck.php | 12 +- .../checks => src/Checks}/SolrIndexCheck.php | 17 ++- {code/checks => src/Checks}/URLCheck.php | 25 ++-- .../Controllers}/DevCheckController.php | 14 +- .../Controllers}/DevHealthController.php | 12 +- {code => src}/EnvironmentCheck.php | 10 +- {code => src}/EnvironmentCheckSuite.php | 125 +++------------- src/EnvironmentCheckSuiteResult.php | 125 ++++++++++++++++ {code => src}/EnvironmentChecker.php | 98 ++++++++----- .../EnvironmentCheck}/EnvironmentChecker.ss | 18 +-- tests/Checks/DatabaseCheckTest.php | 40 +++++ .../ExternalURLCheckTest.php | 12 +- .../FileWritableCheckTest.php | 12 +- .../{checks => Checks}/HasClassCheckTest.php | 12 +- .../HasFunctionCheckTest.php | 14 +- tests/{checks => Checks}/URLCheckTest.php | 12 +- tests/Controllers/DevCheckControllerTest.php | 32 ++++ .../DevHealthControllerTest.php | 20 ++- tests/DevCheckControllerTest.php | 18 --- tests/EnvironmentCheckerTest.php | 57 ++++++-- tests/checks/DatabaseCheckTest.php | 19 --- 37 files changed, 778 insertions(+), 404 deletions(-) create mode 100644 .upgrade.yml create mode 100644 _config/injector.yml rename {code/checks => src/Checks}/DatabaseCheck.php (60%) rename {code/checks => src/Checks}/ExternalURLCheck.php (93%) rename {code/checks => src/Checks}/FileAccessibilityAndValidationCheck.php (83%) rename {code/checks => src/Checks}/FileAgeCheck.php (71%) rename {code/checks => src/Checks}/FileWriteableCheck.php (73%) rename {code/checks => src/Checks}/HasClassCheck.php (69%) rename {code/checks => src/Checks}/HasFunctionCheck.php (68%) rename {code/checks => src/Checks}/SMTPConnectCheck.php (87%) rename {code/checks => src/Checks}/SolrIndexCheck.php (75%) rename {code/checks => src/Checks}/URLCheck.php (78%) rename {code => src/Controllers}/DevCheckController.php (70%) rename {code => src/Controllers}/DevHealthController.php (63%) rename {code => src}/EnvironmentCheck.php (91%) rename {code => src}/EnvironmentCheckSuite.php (68%) create mode 100644 src/EnvironmentCheckSuiteResult.php rename {code => src}/EnvironmentChecker.php (71%) rename templates/{ => SilverStripe/EnvironmentCheck}/EnvironmentChecker.ss (93%) create mode 100644 tests/Checks/DatabaseCheckTest.php rename tests/{checks => Checks}/ExternalURLCheckTest.php (65%) rename tests/{checks => Checks}/FileWritableCheckTest.php (66%) rename tests/{checks => Checks}/HasClassCheckTest.php (67%) rename tests/{checks => Checks}/HasFunctionCheckTest.php (64%) rename tests/{checks => Checks}/URLCheckTest.php (52%) create mode 100644 tests/Controllers/DevCheckControllerTest.php rename tests/{ => Controllers}/DevHealthControllerTest.php (54%) delete mode 100644 tests/DevCheckControllerTest.php delete mode 100644 tests/checks/DatabaseCheckTest.php diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 61b0c9f..de09355 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -6,4 +6,4 @@ checks: duplication: true filter: - paths: [code/*, tests/*] + paths: [src/*, tests/*] diff --git a/.travis.yml b/.travis.yml index 8e741aa..8dddaa1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,33 +1,21 @@ -# See https://github.com/silverstripe-labs/silverstripe-travis-support for setup details +# See https://github.com/silverstripe/silverstripe-travis-support for setup details sudo: false language: php php: - - 5.3 - - 5.4 - 5.5 - 5.6 - 7.0 env: - - DB=MYSQL CORE_RELEASE=3.2 - -matrix: - include: - - php: 5.6 - env: DB=MYSQL CORE_RELEASE=3 - - php: 5.6 - env: DB=MYSQL CORE_RELEASE=3.1 - - php: 5.6 - env: DB=PGSQL CORE_RELEASE=3.2 - allow_failures: - - php: 7.0 + - DB=MYSQL CORE_RELEASE=4 + - DB=PGSQL CORE_RELEASE=4 before_script: - composer self-update || true - - git clone git://github.com/silverstripe-labs/silverstripe-travis-support.git ~/travis-support + - git clone git://github.com/silverstripe/silverstripe-travis-support.git ~/travis-support - php ~/travis-support/travis_setup.php --source `pwd` --target ~/builds/ss - cd ~/builds/ss - composer install diff --git a/.upgrade.yml b/.upgrade.yml new file mode 100644 index 0000000..2087063 --- /dev/null +++ b/.upgrade.yml @@ -0,0 +1,29 @@ +mappings: + EnvironmentCheck: SilverStripe\EnvironmentCheck\EnvironmentCheck + EnvironmentChecker: SilverStripe\EnvironmentCheck\EnvironmentChecker + EnvironmentCheckSuite: SilverStripe\EnvironmentCheck\EnvironmentCheckSuite + EnvironmentCheckSuiteResult: SilverStripe\EnvironmentCheck\EnvironmentCheckSuiteResult + DatabaseCheck: SilverStripe\EnvironmentCheck\Checks\DatabaseCheck + ExternalURLCheck: SilverStripe\EnvironmentCheck\Checks\ExternalURLCheck + FileAccessibilityAndValidationCheck: SilverStripe\EnvironmentCheck\Checks\FileAccessibilityAndValidationCheck + FileAgeCheck: SilverStripe\EnvironmentCheck\Checks\FileAgeCheck + FileWriteableCheck: SilverStripe\EnvironmentCheck\Checks\FileWriteableCheck + HasClassCheck: SilverStripe\EnvironmentCheck\Checks\HasClassCheck + HasFunctionCheck: SilverStripe\EnvironmentCheck\Checks\HasFunctionCheck + SMTPConnectCheck: SilverStripe\EnvironmentCheck\Checks\SMTPConnectCheck + SolrIndexCheck: SilverStripe\EnvironmentCheck\Checks\SolrIndexCheck + URLCheck: SilverStripe\EnvironmentCheck\Checks\URLCheck + DevCheckController: SilverStripe\EnvironmentCheck\Controllers\DevCheckController + DevHealthController: SilverStripe\EnvironmentCheck\Controllers\DevHealthController + EnvironmentCheckerTest: SilverStripe\EnvironmentCheck\Tests\EnvironmentCheckerTest + EnvironmentCheckerTest_CheckNoErrors: SilverStripe\EnvironmentCheck\Tests\EnvironmentCheckerTest_CheckNoErrors + EnvironmentCheckerTest_CheckWarnings: SilverStripe\EnvironmentCheck\Tests\EnvironmentCheckerTest_CheckWarnings + EnvironmentCheckerTest_CheckErrors: SilverStripe\EnvironmentCheck\Tests\EnvironmentCheckerTest_CheckErrors + DatabaseCheckTest: SilverStripe\EnvironmentCheck\Tests\Checks\DatabaseCheckTest + ExternalURLCheckTest: SilverStripe\EnvironmentCheck\Tests\Checks\ExternalURLCheckTest + FileWritableCheckTest: SilverStripe\EnvironmentCheck\Tests\Checks\FileWritableCheckTest + HasClassCheckTest: SilverStripe\EnvironmentCheck\Tests\Checks\HasClassCheckTest + HasFunctionCheckTest: SilverStripe\EnvironmentCheck\Tests\Checks\HasFunctionCheckTest + URLCheckTest: SilverStripe\EnvironmentCheck\Tests\Checks\URLCheckTest + DevCheckControllerTest: SilverStripe\EnvironmentCheck\Tests\Controllers\DevCheckControllerTest + DevHealthControllerTest: SilverStripe\EnvironmentCheck\Tests\Controllers\DevHealthControllerTest diff --git a/_config.php b/_config.php index 69fe792..bfdcd2b 100644 --- a/_config.php +++ b/_config.php @@ -1,5 +1,7 @@ ` - Check a specific suite (admin only) +## Requirements + +* SilverStripe 4.x +* PHP 5.5+ + +For SilverStripe 3.x support, please use a `1.x` tagged release. + ## Aren't these just unit tests? Almost, but not really. Environment checks differ from unit tests in two important ways: @@ -29,11 +36,13 @@ You'll also need to run `/dev/build`. ### Activating Directly -Register checks in your own `_config.php` - see the `_config.php` in this module for some defaults. +Register checks in your own `_config.php` - see the `_config.php` in this module for some defaults. Don't forget to +either use a fully-qualified (namespaced) class name for `EnvironmentCheckSuite`, or `use` (import) the namespaced class +first. ```php -EnvironmentCheckSuite::register('health', 'DatabaseCheck', "Can we connect to the database?"); -EnvironmentCheckSuite::register('check', 'URLCheck("")', "Is the homepage accessible?"); +EnvironmentCheckSuite::register('health', 'DatabaseCheck', 'Can we connect to the database?'); +EnvironmentCheckSuite::register('check', 'URLCheck("")', 'Is the homepage accessible?'); ``` ### Activating Via Config @@ -41,7 +50,7 @@ EnvironmentCheckSuite::register('check', 'URLCheck("")', "Is the homepage access Register your checks on the `EnvironmentCheckSuite`. The same named check may be used multiple times. ```yaml -EnvironmentCheckSuite: +SilverStripe\EnvironmentCheck\EnvironmentCheckSuite: registered_checks: db: definition: 'DatabaseCheck("Page")' @@ -61,7 +70,7 @@ You can also disable checks configured this way. This is handy if you want to ov by some other module. Just set the "state" property of the check to "disabled" like this: ```yaml -EnvironmentCheckSuite: +SilverStripe\EnvironmentCheck\EnvironmentCheckSuite: registered_checks: db: state: disabled @@ -77,7 +86,7 @@ EnvironmentCheckSuite: This can be used to check that PHP modules or features are installed. * `FileWriteableCheck`: Check that the given file is writeable. * `FileAgeCheck`: Checks for the maximum age of one or more files or folders. - Useful for files which should be frequently auto-generated, + Useful for files which should be frequently auto-generated, like static caches, as well as for backup files and folders. * `ExternalURLCheck`: Checks that one or more URLs are reachable via HTTP. * `SMTPConnectCheck`: Checks if the SMTP connection configured through PHP.ini works as expected. @@ -86,23 +95,23 @@ EnvironmentCheckSuite: ## Monitoring Checks Checks will return an appropriate HTTP status code, so are easy to hook into common uptime montoring -solutions like pingdom.com. +solutions like pingdom.com. You can also have the environment checker email results with the following configuration: ```yml -EnvironmentChecker: +SilverStripe\EnvironmentCheck\EnvironmentChecker: email_results: true to_email_address: support@test.com from_email_address: admin@test.com ``` -Errors can be logged via the standard SilverStripe logging. Each check will cause an individual log entry. -You can choose to enable logging separately for warnings and errors, -identified through the result of `EnvironmentCheck->check()`. +Errors can be logged via the standard SilverStripe PSR-3 compatible logging. Each check will cause an individual log +entry. You can choose to enable logging separately for warnings and errors, identified through the +result of `EnvironmentCheck->check()`. ```yml -EnvironmentChecker: +SilverStripe\EnvironmentCheck\EnvironmentChecker: log_results_warning: true log_results_error: true ``` @@ -116,71 +125,88 @@ an administrator on the site. You may wish to have an automated service check `dev/check` periodically, but not want to open it up for public access. You can enable basic authentication by defining the following in your environment: - define('ENVCHECK_BASICAUTH_USERNAME', 'test'); - define('ENVCHECK_BASICAUTH_PASSWORD', 'password'); +```php +define('ENVCHECK_BASICAUTH_USERNAME', 'test'); +define('ENVCHECK_BASICAUTH_PASSWORD', 'password'); +``` Now if you access `dev/check` in a browser it will pop up a basic auth popup, and if the submitted username and password match the ones defined the username and password defined in the environment, access will be granted to the page. ## Adding more checks -To add more checks, you should put additional `EnvironmentCheckSuite::register` calls into your `_config.php`. See the `_config.php` file of this module for examples. +To add more checks, you should put additional `EnvironmentCheckSuite::register` calls into your `_config.php`. +See the `_config.php` file of this module for examples. + +```php +EnvironmentCheckSuite::register('check', 'HasFunctionCheck("curl_init")', "Does PHP have CURL support?"); +EnvironmentCheckSuite::register('check', 'HasFunctionCheck("imagecreatetruecolor")', "Does PHP have GD2 support?"); +``` - :::php - EnvironmentCheckSuite::register('check', 'HasFunctionCheck("curl_init")', "Does PHP have CURL support?"); - EnvironmentCheckSuite::register('check', 'HasFunctionCheck("imagecreatetruecolor")', "Does PHP have GD2 support?"); - The first argument is the name of the check suite. There are two built-in check suites, "health", and "check", corresponding to the `health/check` and `dev/check` URLs. If you wish, you can create your own check suites and execute them on other URLs. You can also add a check to more than one suite by passing the first argument as an array. -The module comes bundled with a few checks in `DefaultHealthChecks.php`. However, to test your own application, you probably want to write custom checks. +To test your own application, you probably want to write custom checks: - * Implement the `EnvironmentCheck` interface + * Implement the `SilverStripe\EnvironmentCheck\EnvironmentCheck` interface * Define the `check()` function, which returns a 2 element array: * The first element is one of `EnvironmentCheck::OK`, `EnvironmentCheck::WARNING`, `EnvironmentCheck::ERROR`, depending on the status of the check * The second element is a string describing the response. Here is a simple example of how you might create a check to test your own code. In this example, we are checking that an instance of the `MyGateway` class will return "foo" when `call()` is called on it. Testing interfaces with 3rd party systems is a common use case for custom environment checks. - :::php - class MyGatewayCheck implements EnvironmentCheck { - protected $checkTable; +```php +use SilverStripe\EnvironmentCheck\EnvironmentCheck; + +class MyGatewayCheck implements EnvironmentCheck +{ + protected $checkTable; + + function check() + { + $g = new \MyGateway; + + $response = $g->call(); + $expectedResponse = 'foo'; + + if($response == null) { + return array(EnvironmentCheck::ERROR, "MyGateway didn't return a response"); + } else if($response != $expectedResponse) { + return array(EnvironmentCheck::WARNING, "MyGateway returned unexpected response $response"); + } + return array(EnvironmentCheck::OK, ''); + } +} +``` - function check() { - $g = new MyGateway; - - $response = $g->call(); - $expectedResponse = "foo"; - - if($response == null) { - return array(EnvironmentCheck::ERROR, "MyGateway didn't return a response"); - } else if($response != $expectedResponse) { - return array(EnvironmentCheck::WARNING, "MyGateway returned unexpected response $response"); - } else { - return array(EnvironmentCheck::OK, ""); - } - } - } - Once you have created your custom check class, don't forget to register it in a check suite - - :::php - EnvironmentCheckSuite::register('check', 'MyGatewayCheck', "Can I connect to the gateway?"); + +```php +EnvironmentCheckSuite::register('check', 'MyGatewayCheck', 'Can I connect to the gateway?'); +``` ### Using other environment check suites -If you want to use the same UI as `health/check` and dev/check, you can create an `EnvironmentChecker` object. This class is a `RequestHandler` and so can be returned from an action handler. The first argument to the `EnvironmentChecker` constructor is the suite name. For example: +If you want to use the same UI as `health/check` and `dev/check`, you can create an `EnvironmentChecker` object. This class is a `RequestHandler` and so can be returned from an action handler. The first argument to the `EnvironmentChecker` constructor is the suite name. For example: - class DevHealth extends Controller { - function index() { - $e = new EnvironmentChecker('health', 'Site health'); - return $e; - } - } - -If you wish to embed an environment check suite in another, you can use the following call. +```php +use SilverStripe\Control\Controller; + +class DevHealth extends Controller +{ + function index() + { + $e = new EnvironmentChecker('health', 'Site health'); + return $e; + } +} +``` + +If you wish to embed an environment check suite in another, you can use the following call: + +```php +$result = EnvironmentCheckSuite::inst('health')->run(); +``` - $result = EnvironmentCheckSuite::inst("health")->run(); - `$result` will contain a `EnvironmentCheckSuiteResult` object * `$result->ShouldPass()`: Return a boolean of whether or not the tests passed. @@ -197,4 +223,4 @@ All methods, with `public` visibility, are part of the public API. All other met ## Reporting Issues -Please [create an issue](http://github.com/silverstripe-labs/silverstripe-environmentcheck/issues) for any bugs you've found, or features you're missing. +Please [create an issue](http://github.com/silverstripe/silverstripe-environmentcheck/issues) for any bugs you've found, or features you're missing. diff --git a/code/checks/DatabaseCheck.php b/src/Checks/DatabaseCheck.php similarity index 60% rename from code/checks/DatabaseCheck.php rename to src/Checks/DatabaseCheck.php index fed416c..86f39d2 100644 --- a/code/checks/DatabaseCheck.php +++ b/src/Checks/DatabaseCheck.php @@ -1,8 +1,15 @@ checkTable = $checkTable; } /** - * @inheritdoc + * {@inheritDoc} * * @return array */ public function check() { - if (!DB::getConn()->hasTable($this->checkTable)) { + if (!DB::get_schema()->hasTable($this->checkTable)) { return array(EnvironmentCheck::ERROR, "$this->checkTable not present in the database"); } $count = DB::query("SELECT COUNT(*) FROM \"$this->checkTable\"")->value(); - + if ($count > 0) { - return array(EnvironmentCheck::OK, ""); - } else { - return array(EnvironmentCheck::WARNING, "$this->checkTable queried ok but has no records"); + return array(EnvironmentCheck::OK, ''); } + + return array(EnvironmentCheck::WARNING, "$this->checkTable queried ok but has no records"); } } diff --git a/code/checks/ExternalURLCheck.php b/src/Checks/ExternalURLCheck.php similarity index 93% rename from code/checks/ExternalURLCheck.php rename to src/Checks/ExternalURLCheck.php index 5b7280f..1047924 100644 --- a/code/checks/ExternalURLCheck.php +++ b/src/Checks/ExternalURLCheck.php @@ -1,12 +1,18 @@ EnvironmentCheckSuite::register('check', 'HasFunctionCheck("curl_init")', "Does PHP have CURL support?"); + * + * @package environmentcheck */ class ExternalURLCheck implements EnvironmentCheck { @@ -33,7 +39,7 @@ class ExternalURLCheck implements EnvironmentCheck } /** - * @inheritdoc + * {@inheritDoc} * * @return array */ @@ -52,7 +58,7 @@ class ExternalURLCheck implements EnvironmentCheck foreach ($chs as $ch) { curl_multi_add_handle($mh, $ch); } - + $active = null; // Execute the handles do { @@ -95,12 +101,12 @@ class ExternalURLCheck implements EnvironmentCheck curl_multi_remove_handle($mh, $ch); } curl_multi_close($mh); - + if ($hasError) { return array(EnvironmentCheck::ERROR, implode(', ', $msgs)); - } else { - return array(EnvironmentCheck::OK, implode(', ', $msgs)); } + + return array(EnvironmentCheck::OK, implode(', ', $msgs)); } /** diff --git a/code/checks/FileAccessibilityAndValidationCheck.php b/src/Checks/FileAccessibilityAndValidationCheck.php similarity index 83% rename from code/checks/FileAccessibilityAndValidationCheck.php rename to src/Checks/FileAccessibilityAndValidationCheck.php index 7c0824d..f37c613 100644 --- a/code/checks/FileAccessibilityAndValidationCheck.php +++ b/src/Checks/FileAccessibilityAndValidationCheck.php @@ -1,5 +1,10 @@ path = $path; - $this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc:'noVidation'; + $this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc : 'noVidation'; $this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE; } /** - * @inheritdoc + * {@inheritDoc} * * @return array */ @@ -91,9 +98,9 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck // If at least one file was valid, count as passed if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) { - $validFileList = "\n"; + $validFileList = PHP_EOL; foreach ($validFiles as $vf) { - $validFileList .= $vf."\n"; + $validFileList .= $vf . PHP_EOL; } if ($fileTypeValidateFunc == 'noVidation') { $checkReturn = array( @@ -103,16 +110,20 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck } else { $checkReturn = array( EnvironmentCheck::OK, - sprintf('At least these file(s) passed file type validate function "%s": %s', $fileTypeValidateFunc, $validFileList) + sprintf( + 'At least these file(s) passed file type validate function "%s": %s', + $fileTypeValidateFunc, + $validFileList + ) ); } } else { if (count($invalidFiles) == 0) { $checkReturn = array(EnvironmentCheck::OK, 'All files valideted'); } else { - $invalidFileList = "\n"; + $invalidFileList = PHP_EOL; foreach ($invalidFiles as $vf) { - $invalidFileList .= $vf."\n"; + $invalidFileList .= $vf . PHP_EOL; } if ($fileTypeValidateFunc == 'noVidation') { @@ -123,7 +134,11 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck } else { $checkReturn = array( EnvironmentCheck::ERROR, - sprintf('File(s) not passing the file type validate function "%s": %s', $fileTypeValidateFunc, $invalidFileList) + sprintf( + 'File(s) not passing the file type validate function "%s": %s', + $fileTypeValidateFunc, + $invalidFileList + ) ); } } @@ -156,9 +171,8 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck $json = json_decode(file_get_contents($file)); if (!$json) { return false; - } else { - return true; } + return true; } /** diff --git a/code/checks/FileAgeCheck.php b/src/Checks/FileAgeCheck.php similarity index 71% rename from code/checks/FileAgeCheck.php rename to src/Checks/FileAgeCheck.php index 55a6873..483ebe4 100644 --- a/code/checks/FileAgeCheck.php +++ b/src/Checks/FileAgeCheck.php @@ -1,23 +1,30 @@ ', " . FileAgeCheck::CHECK_ALL) . "' + * 'check', + * 'FileAgeCheck("' . ASSETS_PATH . '/_combined_files/*.js' . '", "-1 day", '>', " . FileAgeCheck::CHECK_ALL) . "' * ); - * + * * // Checks that at least one backup folder has been created in the last 24h * EnvironmentCheckSuite::register( - * 'check', - * 'FileAgeCheck("' . BASE_PATH . '/../backups/*' . '", "-1 day", '>', " . FileAgeCheck::CHECK_SINGLE) . "' + * 'check', + * 'FileAgeCheck("' . BASE_PATH . '/../backups/*' . '", "-1 day", '>', " . FileAgeCheck::CHECK_SINGLE) . "' * ); + * + * @package environmentcheck */ class FileAgeCheck implements EnvironmentCheck { @@ -30,7 +37,7 @@ class FileAgeCheck implements EnvironmentCheck * @var int */ const CHECK_ALL = 2; - + /** * Absolute path to a file or folder, compatible with glob(). * @@ -83,13 +90,13 @@ class FileAgeCheck implements EnvironmentCheck } /** - * @inheritdoc + * {@inheritDoc} * * @return array */ public function check() { - $cutoffTime = strtotime($this->relativeAge, SS_Datetime::now()->Format('U')); + $cutoffTime = strtotime($this->relativeAge, DBDatetime::now()->Format('U')); $files = $this->getFiles(); $invalidFiles = array(); $validFiles = array(); @@ -105,12 +112,15 @@ class FileAgeCheck implements EnvironmentCheck $invalidFiles[] = $file; if ($this->checkType == self::CHECK_ALL) { return array( - EnvironmentCheck::ERROR, - sprintf( - 'File "%s" doesn\'t match age check (compare %s: %s, actual: %s)', - $file, $this->compareOperand, date('c', $cutoffTime), date('c', $fileTime) - ) - ); + EnvironmentCheck::ERROR, + sprintf( + 'File "%s" doesn\'t match age check (compare %s: %s, actual: %s)', + $file, + $this->compareOperand, + date('c', $cutoffTime), + date('c', $fileTime) + ) + ); } } } @@ -119,16 +129,14 @@ class FileAgeCheck implements EnvironmentCheck // If at least one file was valid, count as passed if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) { return array(EnvironmentCheck::OK, ''); - } else { - if (count($invalidFiles) == 0) { - return array(EnvironmentCheck::OK, ''); - } else { - return array( - EnvironmentCheck::ERROR, - sprintf('No files matched criteria (%s %s)', $this->compareOperand, date('c', $cutoffTime)) - ); - } } + if (count($invalidFiles) == 0) { + return array(EnvironmentCheck::OK, ''); + } + return array( + EnvironmentCheck::ERROR, + sprintf('No files matched criteria (%s %s)', $this->compareOperand, date('c', $cutoffTime)) + ); } /** diff --git a/code/checks/FileWriteableCheck.php b/src/Checks/FileWriteableCheck.php similarity index 73% rename from code/checks/FileWriteableCheck.php rename to src/Checks/FileWriteableCheck.php index 6c837d8..a369ad7 100644 --- a/code/checks/FileWriteableCheck.php +++ b/src/Checks/FileWriteableCheck.php @@ -1,7 +1,13 @@ path); } - + if (file_exists($filename)) { $isWriteable = is_writeable($filename); } else { $isWriteable = is_writeable(dirname($filename)); } - + if (!$isWriteable) { if (function_exists('posix_getgroups')) { $userID = posix_geteuid(); @@ -45,10 +51,11 @@ class FileWriteableCheck implements EnvironmentCheck $currentOwnerID = fileowner(file_exists($filename) ? $filename : dirname($filename)); $currentOwner = posix_getpwuid($currentOwnerID); - $message = "User '$user[name]' needs to be able to write to this file:\n$filename\n\nThe file is currently owned by '$currentOwner[name]'. "; + $message = "User '$user[name]' needs to be able to write to this file:\n$filename\n\nThe file is " + . "currently owned by '$currentOwner[name]'. "; if ($user['name'] == $currentOwner['name']) { - $message .= "We recommend that you make the file writeable."; + $message .= 'We recommend that you make the file writeable.'; } else { $groups = posix_getgroups(); $groupList = array(); @@ -59,19 +66,22 @@ class FileWriteableCheck implements EnvironmentCheck } } if ($groupList) { - $message .= " We recommend that you make the file group-writeable and change the group to one of these groups:\n - ". implode("\n - ", $groupList) + $message .= " We recommend that you make the file group-writeable and change the group to " + . "one of these groups:\n - " . implode("\n - ", $groupList) . "\n\nFor example:\nchmod g+w $filename\nchgrp " . $groupList[0] . " $filename"; } else { - $message .= " There is no user-group that contains both the web-server user and the owner of this file. Change the ownership of the file, create a new group, or temporarily make the file writeable by everyone during the install process."; + $message .= " There is no user-group that contains both the web-server user and the owner " + . "of this file. Change the ownership of the file, create a new group, or temporarily " + . "make the file writeable by everyone during the install process."; } } } else { $message = "The webserver user needs to be able to write to this file:\n$filename"; } - + return array(EnvironmentCheck::ERROR, $message); } - return array(EnvironmentCheck::OK,''); + return array(EnvironmentCheck::OK, ''); } } diff --git a/code/checks/HasClassCheck.php b/src/Checks/HasClassCheck.php similarity index 69% rename from code/checks/HasClassCheck.php rename to src/Checks/HasClassCheck.php index bf2b12a..ad3438b 100644 --- a/code/checks/HasClassCheck.php +++ b/src/Checks/HasClassCheck.php @@ -1,7 +1,13 @@ className)) { return array(EnvironmentCheck::OK, 'Class ' . $this->className.' exists'); - } else { - return array(EnvironmentCheck::ERROR, 'Class ' . $this->className.' doesn\'t exist'); } + return array(EnvironmentCheck::ERROR, 'Class ' . $this->className.' doesn\'t exist'); } } diff --git a/code/checks/HasFunctionCheck.php b/src/Checks/HasFunctionCheck.php similarity index 68% rename from code/checks/HasFunctionCheck.php rename to src/Checks/HasFunctionCheck.php index b0f3c1c..4d7a4a2 100644 --- a/code/checks/HasFunctionCheck.php +++ b/src/Checks/HasFunctionCheck.php @@ -1,7 +1,13 @@ functionName)) { - return array(EnvironmentCheck::OK, $this->functionName.'() exists'); - } else { - return array(EnvironmentCheck::ERROR, $this->functionName.'() doesn\'t exist'); + return array(EnvironmentCheck::OK, $this->functionName . '() exists'); } + return array(EnvironmentCheck::ERROR, $this->functionName . '() doesn\'t exist'); } } diff --git a/code/checks/SMTPConnectCheck.php b/src/Checks/SMTPConnectCheck.php similarity index 87% rename from code/checks/SMTPConnectCheck.php rename to src/Checks/SMTPConnectCheck.php index 19f069c..6e6fb2f 100644 --- a/code/checks/SMTPConnectCheck.php +++ b/src/Checks/SMTPConnectCheck.php @@ -1,9 +1,15 @@ host) { $this->host = 'localhost'; } - + $this->port = ($port) ? $port : ini_get('smtp_port'); if (!$this->port) { $this->port = 25; @@ -45,7 +51,7 @@ class SMTPConnectCheck implements EnvironmentCheck } /** - * @inheritdoc + * {@inheritDoc} * * @return array */ @@ -64,7 +70,7 @@ class SMTPConnectCheck implements EnvironmentCheck if (substr($response, 0, 3) != '220') { return array( EnvironmentCheck::ERROR, - sprintf("Invalid mail server response: %s", $response) + sprintf('Invalid mail server response: %s', $response) ); } diff --git a/code/checks/SolrIndexCheck.php b/src/Checks/SolrIndexCheck.php similarity index 75% rename from code/checks/SolrIndexCheck.php rename to src/Checks/SolrIndexCheck.php index 1aaea6b..fd6590f 100644 --- a/code/checks/SolrIndexCheck.php +++ b/src/Checks/SolrIndexCheck.php @@ -1,9 +1,15 @@ indexClass) as $index) { + $service = \Solr::service(); + foreach (\Solr::get_indexes($this->indexClass) as $index) { $core = $index->getIndexName(); if (!$service->coreIsActive($core)) { $brokenCores[] = $core; diff --git a/code/checks/URLCheck.php b/src/Checks/URLCheck.php similarity index 78% rename from code/checks/URLCheck.php rename to src/Checks/URLCheck.php index c9b6353..fd7f6cd 100644 --- a/code/checks/URLCheck.php +++ b/src/Checks/URLCheck.php @@ -1,9 +1,16 @@ url, $this->testString) ); - } else { - return array( - EnvironmentCheck::OK, - sprintf('Success retrieving "%s"', $this->url) - ); } + return array( + EnvironmentCheck::OK, + sprintf('Success retrieving "%s"', $this->url) + ); } } diff --git a/code/DevCheckController.php b/src/Controllers/DevCheckController.php similarity index 70% rename from code/DevCheckController.php rename to src/Controllers/DevCheckController.php index 6a292b2..c26c338 100644 --- a/code/DevCheckController.php +++ b/src/Controllers/DevCheckController.php @@ -1,5 +1,15 @@ run(); + * + * @package environmentcheck */ class EnvironmentCheckSuite extends Object { @@ -77,10 +89,10 @@ class EnvironmentCheckSuite extends Object // Existing named checks can be disabled by setting their 'state' to 'disabled'. // This is handy for disabling checks mandated by modules. - if (!empty($check['state']) && $check['state']==='disabled') { + if (!empty($check['state']) && $check['state'] === 'disabled') { continue; } - + // Add the check to this suite. $this->push($check['definition'], $check['title']); } @@ -114,6 +126,7 @@ class EnvironmentCheckSuite extends Object * Get instances of all the environment checks. * * @return array + * @throws InvalidArgumentException */ protected function checkInstances() { @@ -125,7 +138,9 @@ class EnvironmentCheckSuite extends Object if ($checkInst instanceof EnvironmentCheck) { $output[] = array($checkInst, $checkTitle); } else { - throw new InvalidArgumentException("Bad EnvironmentCheck: '$checkClass' - the named class doesn't implement EnvironmentCheck"); + throw new InvalidArgumentException( + "Bad EnvironmentCheck: '$checkClass' - the named class doesn't implement EnvironmentCheck" + ); } } elseif ($checkClass instanceof EnvironmentCheck) { $output[] = array($checkClass, $checkTitle); @@ -184,6 +199,7 @@ class EnvironmentCheckSuite extends Object if (!is_array($names)) { $names = array($names); } + foreach ($names as $name) { self::inst($name)->push($check, $title); } @@ -197,106 +213,3 @@ class EnvironmentCheckSuite extends Object self::$instances = array(); } } - -/** - * A single set of results from running an EnvironmentCheckSuite - */ -class EnvironmentCheckSuiteResult extends ViewableData -{ - /** - * @var ArrayList - */ - protected $details; - - /** - * @var int - */ - protected $worst = 0; - - public function __construct() - { - parent::__construct(); - $this->details = new ArrayList(); - } - - /** - * @param int $status - * @param string $message - * @param string $checkIdentifier - */ - public function addResult($status, $message, $checkIdentifier) - { - $this->details->push(new ArrayData(array( - 'Check' => $checkIdentifier, - 'Status' => $this->statusText($status), - 'StatusCode' => $status, - 'Message' => $message, - ))); - - $this->worst = max($this->worst, $status); - } - - /** - * Returns true if there are no errors. - * - * @return bool - */ - public function ShouldPass() - { - return $this->worst <= EnvironmentCheck::WARNING; - } - - /** - * Returns overall (i.e. worst) status as a string. - * - * @return string - */ - public function Status() - { - return $this->statusText($this->worst); - } - - /** - * Returns detailed status information about each check. - * - * @return ArrayList - */ - public function Details() - { - return $this->details; - } - - /** - * Convert the final result status and details to JSON. - * - * @return string - */ - public function toJSON() - { - $result = array( - 'Status' => $this->Status(), - 'ShouldPass' => $this->ShouldPass(), - 'Checks' => array() - ); - foreach ($this->details as $detail) { - $result['Checks'][] = $detail->toMap(); - } - return json_encode($result); - } - - /** - * Return a text version of a status code. - * - * @return string - */ - protected function statusText($status) - { - switch ($status) { - case EnvironmentCheck::ERROR: return "ERROR"; - case EnvironmentCheck::WARNING: return "WARNING"; - case EnvironmentCheck::OK: return "OK"; - case 0: return "NO CHECKS"; - default: throw new InvalidArgumentException("Bad environment check status '$status'"); - } - } -} diff --git a/src/EnvironmentCheckSuiteResult.php b/src/EnvironmentCheckSuiteResult.php new file mode 100644 index 0000000..8a8fa26 --- /dev/null +++ b/src/EnvironmentCheckSuiteResult.php @@ -0,0 +1,125 @@ +details = new ArrayList(); + } + + /** + * @param int $status + * @param string $message + * @param string $checkIdentifier + */ + public function addResult($status, $message, $checkIdentifier) + { + $this->details->push(new ArrayData(array( + 'Check' => $checkIdentifier, + 'Status' => $this->statusText($status), + 'StatusCode' => $status, + 'Message' => $message, + ))); + + $this->worst = max($this->worst, $status); + } + + /** + * Returns true if there are no errors. + * + * @return bool + */ + public function ShouldPass() + { + return $this->worst <= EnvironmentCheck::WARNING; + } + + /** + * Returns overall (i.e. worst) status as a string. + * + * @return string + */ + public function Status() + { + return $this->statusText($this->worst); + } + + /** + * Returns detailed status information about each check. + * + * @return ArrayList + */ + public function Details() + { + return $this->details; + } + + /** + * Convert the final result status and details to JSON. + * + * @return string + */ + public function toJSON() + { + $result = array( + 'Status' => $this->Status(), + 'ShouldPass' => $this->ShouldPass(), + 'Checks' => array() + ); + foreach ($this->details as $detail) { + $result['Checks'][] = $detail->toMap(); + } + return json_encode($result); + } + + /** + * Return a text version of a status code. + * + * @param int $status + * @return string + * @throws InvalidArgumentException + */ + protected function statusText($status) + { + switch ($status) { + case EnvironmentCheck::ERROR: + return 'ERROR'; + break; + case EnvironmentCheck::WARNING: + return 'WARNING'; + break; + case EnvironmentCheck::OK: + return 'OK'; + break; + case 0: + return 'NO CHECKS'; + break; + default: + throw new InvalidArgumentException("Bad environment check status '$status'"); + break; + } + } +} diff --git a/code/EnvironmentChecker.php b/src/EnvironmentChecker.php similarity index 71% rename from code/EnvironmentChecker.php rename to src/EnvironmentChecker.php index 1acfb42..7766111 100644 --- a/code/EnvironmentChecker.php +++ b/src/EnvironmentChecker.php @@ -1,7 +1,26 @@ checkSuiteName = $checkSuiteName; $this->title = $title; } @@ -77,7 +96,7 @@ class EnvironmentChecker extends RequestHandler /** * @param string $permission * - * @throws SS_HTTPResponse_Exception + * @throws HTTPResponse_Exception */ public function init($permission = 'ADMIN') { @@ -85,24 +104,23 @@ class EnvironmentChecker extends RequestHandler if (defined('ENVCHECK_BASICAUTH_USERNAME') && defined('ENVCHECK_BASICAUTH_PASSWORD')) { if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { // authenticate the input user/pass with the configured credentials - if ( - !( + if (!( $_SERVER['PHP_AUTH_USER'] == ENVCHECK_BASICAUTH_USERNAME && $_SERVER['PHP_AUTH_PW'] == ENVCHECK_BASICAUTH_PASSWORD ) ) { - $response = new SS_HTTPResponse(null, 401); + $response = new HTTPResponse(null, 401); $response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\""); // Exception is caught by RequestHandler->handleRequest() and will halt further execution - $e = new SS_HTTPResponse_Exception(null, 401); + $e = new HTTPResponse_Exception(null, 401); $e->setResponse($response); throw $e; } } else { - $response = new SS_HTTPResponse(null, 401); + $response = new HTTPResponse(null, 401); $response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\""); // Exception is caught by RequestHandler->handleRequest() and will halt further execution - $e = new SS_HTTPResponse_Exception(null, 401); + $e = new HTTPResponse_Exception(null, 401); $e->setResponse($response); throw $e; } @@ -119,9 +137,9 @@ class EnvironmentChecker extends RequestHandler * * @return bool * - * @throws SS_HTTPResponse_Exception + * @throws HTTPResponse_Exception */ - public function canAccess($member = null, $permission = "ADMIN") + public function canAccess($member = null, $permission = 'ADMIN') { if (!$member) { $member = Member::currentUser(); @@ -133,8 +151,7 @@ class EnvironmentChecker extends RequestHandler // We allow access to this controller regardless of live-status or ADMIN permission only // if on CLI. Access to this controller is always allowed in "dev-mode", or of the user is ADMIN. - if ( - Director::isDev() + if (Director::isDev() || Director::is_cli() || empty($permission) || Permission::checkMember($member, $permission) @@ -149,20 +166,19 @@ class EnvironmentChecker extends RequestHandler if ($results && is_array($results)) { if (!min($results)) { return false; - } else { - return true; } + return true; } return false; } /** - * @return SS_HTTPResponse + * @return HTTPResponse */ public function index() { - $response = new SS_HTTPResponse; + $response = new HTTPResponse; $result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run(); if (!$result->ShouldPass()) { @@ -170,14 +186,19 @@ class EnvironmentChecker extends RequestHandler } $resultText = $result->customise(array( - "URL" => Director::absoluteBaseURL(), - "Title" => $this->title, - "Name" => $this->checkSuiteName, - "ErrorCode" => $this->errorCode, - ))->renderWith("EnvironmentChecker"); + 'URL' => Director::absoluteBaseURL(), + 'Title' => $this->title, + 'Name' => $this->checkSuiteName, + 'ErrorCode' => $this->errorCode, + ))->renderWith(__CLASS__); if ($this->config()->email_results && !$result->ShouldPass()) { - $email = new Email($this->config()->from_email_address, $this->config()->to_email_address, $this->title, $resultText); + $email = new Email( + $this->config()->from_email_address, + $this->config()->to_email_address, + $this->title, + $resultText + ); $email->send(); } @@ -197,8 +218,7 @@ class EnvironmentChecker extends RequestHandler } // output the result as JSON if requested - if ( - $this->getRequest()->getExtension() == 'json' + if ($this->getRequest()->getExtension() == 'json' || strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false ) { $response->setBody($result->toJSON()); @@ -207,17 +227,19 @@ class EnvironmentChecker extends RequestHandler } $response->setBody($resultText); - + return $response; } /** + * Sends a log entry to the configured PSR-3 LoggerInterface + * * @param string $message * @param int $level */ public function log($message, $level) { - SS_Log::log($message, $level); + Injector::inst()->get('Logger')->log($level, $message); } /** @@ -237,7 +259,7 @@ class EnvironmentChecker extends RequestHandler public static function set_from_email_address($from) { Deprecation::notice('2.0', 'Use config API instead'); - Config::inst()->update('EnvironmentChecker', 'from_email_address', $from); + Config::inst()->update(__CLASS__, 'from_email_address', $from); } /** @@ -247,7 +269,7 @@ class EnvironmentChecker extends RequestHandler public static function get_from_email_address() { Deprecation::notice('2.0', 'Use config API instead'); - return Config::inst()->get('EnvironmentChecker', 'from_email_address'); + return Config::inst()->get(__CLASS__, 'from_email_address'); } /** @@ -257,7 +279,7 @@ class EnvironmentChecker extends RequestHandler public static function set_to_email_address($to) { Deprecation::notice('2.0', 'Use config API instead'); - Config::inst()->update('EnvironmentChecker', 'to_email_address', $to); + Config::inst()->update(__CLASS__, 'to_email_address', $to); } /** @@ -267,7 +289,7 @@ class EnvironmentChecker extends RequestHandler public static function get_to_email_address() { Deprecation::notice('2.0', 'Use config API instead'); - return Config::inst()->get('EnvironmentChecker', 'to_email_address'); + return Config::inst()->get(__CLASS__, 'to_email_address'); } /** @@ -277,7 +299,7 @@ class EnvironmentChecker extends RequestHandler public static function set_email_results($results) { Deprecation::notice('2.0', 'Use config API instead'); - Config::inst()->update('EnvironmentChecker', 'email_results', $results); + Config::inst()->update(__CLASS__, 'email_results', $results); } /** @@ -287,6 +309,6 @@ class EnvironmentChecker extends RequestHandler public static function get_email_results() { Deprecation::notice('2.0', 'Use config API instead'); - return Config::inst()->get('EnvironmentChecker', 'email_results'); + return Config::inst()->get(__CLASS__, 'email_results'); } } diff --git a/templates/EnvironmentChecker.ss b/templates/SilverStripe/EnvironmentCheck/EnvironmentChecker.ss similarity index 93% rename from templates/EnvironmentChecker.ss rename to templates/SilverStripe/EnvironmentCheck/EnvironmentChecker.ss index a41eeb3..8704131 100644 --- a/templates/EnvironmentChecker.ss +++ b/templates/SilverStripe/EnvironmentCheck/EnvironmentChecker.ss @@ -10,7 +10,7 @@ margin-top: -10px; font-size: 10px; } - + h1 { font-size: 30px; margin-bottom: 3px; @@ -21,11 +21,11 @@ font-size: 16px; margin: 2px 0 10px 8px; } - + p { margin-left: 10px; } - + table { border-collapse: collapse; } @@ -44,7 +44,7 @@ table tr:nth-child(odd) td { background-color: #ddd; } - + .OK { color: green; } @@ -59,23 +59,23 @@ - +

$Title: $Status

Site: $URL

- + - <% loop Details %> + <% loop $Details %> <% end_loop %>
Check Status Message
$Check $Status $Message.XML
- <% if ShouldPass %> + <% if $ShouldPass %>

Site is available

(you may check for the presence of the text 'Site is available' rather than an HTTP $ErrorCode error on this page, if you prefer.)

<% else %> - <% if Name == check %> + <% if $Name == "check" %>

A subsystem of the site is unavailable, but the site remains operational

<% else %>

Site is not available

diff --git a/tests/Checks/DatabaseCheckTest.php b/tests/Checks/DatabaseCheckTest.php new file mode 100644 index 0000000..6743054 --- /dev/null +++ b/tests/Checks/DatabaseCheckTest.php @@ -0,0 +1,40 @@ +FirstName = 'Bob'; + $member->write(); + + $check = new DatabaseCheck(); + + $expected = array( + EnvironmentCheck::OK, + '' + ); + + $this->assertEquals($expected, $check->check()); + } +} diff --git a/tests/checks/ExternalURLCheckTest.php b/tests/Checks/ExternalURLCheckTest.php similarity index 65% rename from tests/checks/ExternalURLCheckTest.php rename to tests/Checks/ExternalURLCheckTest.php index 50984ab..66b60f1 100644 --- a/tests/checks/ExternalURLCheckTest.php +++ b/tests/Checks/ExternalURLCheckTest.php @@ -1,7 +1,17 @@ assertEquals($expected, $check->check()); diff --git a/tests/checks/FileWritableCheckTest.php b/tests/Checks/FileWritableCheckTest.php similarity index 66% rename from tests/checks/FileWritableCheckTest.php rename to tests/Checks/FileWritableCheckTest.php index 8cf4c7b..4709c47 100644 --- a/tests/checks/FileWritableCheckTest.php +++ b/tests/Checks/FileWritableCheckTest.php @@ -1,7 +1,17 @@ assertEquals($expected, $check->check()); diff --git a/tests/checks/HasClassCheckTest.php b/tests/Checks/HasClassCheckTest.php similarity index 67% rename from tests/checks/HasClassCheckTest.php rename to tests/Checks/HasClassCheckTest.php index 7d8132a..c4fb77a 100644 --- a/tests/checks/HasClassCheckTest.php +++ b/tests/Checks/HasClassCheckTest.php @@ -1,7 +1,17 @@ assertEquals($expected, $check->check()); diff --git a/tests/checks/HasFunctionCheckTest.php b/tests/Checks/HasFunctionCheckTest.php similarity index 64% rename from tests/checks/HasFunctionCheckTest.php rename to tests/Checks/HasFunctionCheckTest.php index c1857a5..cb1533f 100644 --- a/tests/checks/HasFunctionCheckTest.php +++ b/tests/Checks/HasFunctionCheckTest.php @@ -1,7 +1,17 @@ assertEquals($expected, $check->check()); @@ -23,7 +33,7 @@ class HasFunctionCheckTest extends SapphireTest $expected = array( EnvironmentCheck::OK, - 'class_exists() exists', + 'class_exists() exists' ); $this->assertEquals($expected, $check->check()); diff --git a/tests/checks/URLCheckTest.php b/tests/Checks/URLCheckTest.php similarity index 52% rename from tests/checks/URLCheckTest.php rename to tests/Checks/URLCheckTest.php index 2276f69..2f8f7b5 100644 --- a/tests/checks/URLCheckTest.php +++ b/tests/Checks/URLCheckTest.php @@ -1,7 +1,17 @@ assertEquals($expected, $check->check()); diff --git a/tests/Controllers/DevCheckControllerTest.php b/tests/Controllers/DevCheckControllerTest.php new file mode 100644 index 0000000..4ab71be --- /dev/null +++ b/tests/Controllers/DevCheckControllerTest.php @@ -0,0 +1,32 @@ +assertInstanceOf('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', $controller->index($request)); + } +} diff --git a/tests/DevHealthControllerTest.php b/tests/Controllers/DevHealthControllerTest.php similarity index 54% rename from tests/DevHealthControllerTest.php rename to tests/Controllers/DevHealthControllerTest.php index 59e240e..e303cbd 100644 --- a/tests/DevHealthControllerTest.php +++ b/tests/Controllers/DevHealthControllerTest.php @@ -1,17 +1,31 @@ assertInstanceOf('EnvironmentChecker', $controller->index($request)); + $this->assertInstanceOf('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', $controller->index($request)); } } diff --git a/tests/DevCheckControllerTest.php b/tests/DevCheckControllerTest.php deleted file mode 100644 index eb99e55..0000000 --- a/tests/DevCheckControllerTest.php +++ /dev/null @@ -1,18 +0,0 @@ -assertInstanceOf('EnvironmentChecker', $controller->index($request)); - } -} diff --git a/tests/EnvironmentCheckerTest.php b/tests/EnvironmentCheckerTest.php index f23227e..2e38538 100644 --- a/tests/EnvironmentCheckerTest.php +++ b/tests/EnvironmentCheckerTest.php @@ -1,15 +1,47 @@ get('Logger'); + if ($logger instanceof \Monolog\Logger) { + // It logs to stderr by default - disable + $logger->pushHandler(new \Monolog\Handler\NullHandler); + } } + /** + * {@inheritDoc} + */ public function setUp() { parent::setUp(); @@ -17,6 +49,9 @@ class EnvironmentCheckerTest extends SapphireTest Config::nest(); } + /** + * {@inheritDoc} + */ public function tearDown() { Config::unnest(); @@ -26,11 +61,11 @@ class EnvironmentCheckerTest extends SapphireTest public function testOnlyLogsWithErrors() { - Config::inst()->update('EnvironmentChecker', 'log_results_warning', true); - Config::inst()->update('EnvironmentChecker', 'log_results_error', true); + Config::inst()->update('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'log_results_warning', true); + Config::inst()->update('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'log_results_error', true); EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckNoErrors()); $checker = Phockito::spy( - 'EnvironmentChecker', + 'SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'test suite', 'test' ); @@ -42,12 +77,12 @@ class EnvironmentCheckerTest extends SapphireTest public function testLogsWithWarnings() { - Config::inst()->update('EnvironmentChecker', 'log_results_warning', true); - Config::inst()->update('EnvironmentChecker', 'log_results_error', false); + Config::inst()->update('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'log_results_warning', true); + Config::inst()->update('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'log_results_error', false); EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckWarnings()); EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckErrors()); $checker = Phockito::spy( - 'EnvironmentChecker', + 'SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'test suite', 'test' ); @@ -60,12 +95,12 @@ class EnvironmentCheckerTest extends SapphireTest public function testLogsWithErrors() { - Config::inst()->update('EnvironmentChecker', 'log_results_error', false); - Config::inst()->update('EnvironmentChecker', 'log_results_error', true); + Config::inst()->update('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'log_results_error', false); + Config::inst()->update('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'log_results_error', true); EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckWarnings()); EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckErrors()); $checker = Phockito::spy( - 'EnvironmentChecker', + 'SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'test suite', 'test' ); @@ -89,7 +124,7 @@ class EnvironmentCheckerTest_CheckWarnings implements EnvironmentCheck, TestOnly { public function check() { - return array(EnvironmentCheck::WARNING, "test warning"); + return array(EnvironmentCheck::WARNING, 'test warning'); } } @@ -97,6 +132,6 @@ class EnvironmentCheckerTest_CheckErrors implements EnvironmentCheck, TestOnly { public function check() { - return array(EnvironmentCheck::ERROR, "test error"); + return array(EnvironmentCheck::ERROR, 'test error'); } } diff --git a/tests/checks/DatabaseCheckTest.php b/tests/checks/DatabaseCheckTest.php deleted file mode 100644 index ee571df..0000000 --- a/tests/checks/DatabaseCheckTest.php +++ /dev/null @@ -1,19 +0,0 @@ -assertEquals($expected, $check->check()); - } -}