PSR-2 formatting updates, separate Result from CheckSuite, implement PSR-3 logging, fix tests

This commit is contained in:
Robbie Averill 2016-12-22 15:59:50 +13:00
parent f9d5f61e8b
commit 8a1695073b
26 changed files with 403 additions and 375 deletions

View File

@ -2,16 +2,14 @@
namespace SilverStripe\EnvironmentCheck\Checks;
use SilverStripe\ORM\DB;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\ORM\DB;
/**
* Check that the connection to the database is working, by ensuring that the table exists and that
* the table contains some records.
*
* @package environmentcheck
*/
class DatabaseCheck implements EnvironmentCheck
{
@ -22,28 +20,28 @@ class DatabaseCheck implements EnvironmentCheck
*
* @param string $checkTable
*/
public function __construct($checkTable = "SilverStripe\\Security\\Member")
public function __construct($checkTable = 'Member')
{
$this->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");
}
}

View File

@ -2,18 +2,17 @@
namespace SilverStripe\EnvironmentCheck\Checks;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
/**
* Checks that one or more URLs are reachable via HTTP.
* Note that the HTTP connectivity can just be verified from the server to the remote URL,
* it can still fail if the URL in question is requested by the client, e.g. through an iframe.
*
*
* Requires curl to present, so ensure to check it before with the following:
* <code>EnvironmentCheckSuite::register('check', 'HasFunctionCheck("curl_init")', "Does PHP have CURL support?");</code>
*
* @package environmentcheck
*/
class ExternalURLCheck implements EnvironmentCheck
{
@ -40,7 +39,7 @@ class ExternalURLCheck implements EnvironmentCheck
}
/**
* @inheritdoc
* {@inheritDoc}
*
* @return array
*/
@ -59,7 +58,7 @@ class ExternalURLCheck implements EnvironmentCheck
foreach ($chs as $ch) {
curl_multi_add_handle($mh, $ch);
}
$active = null;
// Execute the handles
do {
@ -102,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));
}
/**

View File

@ -2,12 +2,8 @@
namespace SilverStripe\EnvironmentCheck\Checks;
use SilverStripe\ORM\Versioning\Versioned;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\ORM\Versioning\Versioned;
/**
* Checks for the accessibility and file type validation of one or more files or folders.
@ -17,16 +13,18 @@ use SilverStripe\EnvironmentCheck\EnvironmentCheck;
* EnvironmentCheckSuite::register('check', 'FileAccessibilityAndValidationCheck("' . BASE_PATH . '/assets/calculator_files/*.json",
* "jsonValidate", '.FileAccessibilityAndValidationCheck::CHECK_ALL.')', 'Check a json file exist and are all valid json files'
* );
*
*
* // Checks /assets/calculator_files/calculator.json exists and is valid json file.
* EnvironmentCheckSuite::register('check', 'FileAccessibilityAndValidationCheck("' . BASE_PATH . '/assets/calculator_files/calculator.json",
* "jsonValidate", '.FileAccessibilityAndValidationCheck::CHECK_SINGLE.')', 'Check a calculator.json exists and is valid json file'
* );
*
* // Check only existence
* // Check only existence
* EnvironmentCheckSuite::register('check', 'FileAccessibilityAndValidationCheck("' . BASE_PATH . '/assets/calculator_files/calculator.json")',
* 'Check a calculator.json exists only'
* );
*
* @package environmentcheck
*/
class FileAccessibilityAndValidationCheck implements EnvironmentCheck
{
@ -69,12 +67,12 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck
public function __construct($path, $fileTypeValidateFunc = 'noVidation', $checkType = null)
{
$this->path = $path;
$this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc:'noVidation';
$this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc : 'noVidation';
$this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
}
/**
* @inheritdoc
* {@inheritDoc}
*
* @return array
*/
@ -100,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(
@ -112,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') {
@ -132,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
)
);
}
}
@ -165,9 +171,8 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck
$json = json_decode(file_get_contents($file));
if (!$json) {
return false;
} else {
return true;
}
return true;
}
/**

View File

@ -2,31 +2,29 @@
namespace SilverStripe\EnvironmentCheck\Checks;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\ORM\FieldType\DBDatetime;
/**
* 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.
* Does NOT check for existence of a file (will silently fail).
*
* Examples:
* // Checks that Requirements::combine_files() has regenerated files in the last 24h
* EnvironmentCheckSuite::register(
* 'check',
* 'FileAgeCheck("' . ASSETS_PATH . '/_combined_files/*.js' . '", "-1 day", '>', " . 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
{
@ -39,7 +37,7 @@ class FileAgeCheck implements EnvironmentCheck
* @var int
*/
const CHECK_ALL = 2;
/**
* Absolute path to a file or folder, compatible with glob().
*
@ -92,7 +90,7 @@ class FileAgeCheck implements EnvironmentCheck
}
/**
* @inheritdoc
* {@inheritDoc}
*
* @return array
*/
@ -114,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)
)
);
}
}
}
@ -128,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))
);
}
/**

View File

@ -2,13 +2,12 @@
namespace SilverStripe\EnvironmentCheck\Checks;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
/**
* Check that the given file is writable.
*
* @package environmentcheck
*/
class FileWriteableCheck implements EnvironmentCheck
{
@ -26,7 +25,7 @@ class FileWriteableCheck implements EnvironmentCheck
}
/**
* @inheritdoc
* {@inheritDoc}
*
* @return array
*/
@ -37,13 +36,13 @@ class FileWriteableCheck implements EnvironmentCheck
} else {
$filename = BASE_PATH . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $this->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();
@ -52,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();
@ -66,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, '');
}
}

View File

@ -2,13 +2,12 @@
namespace SilverStripe\EnvironmentCheck\Checks;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
/**
* Check that the given class exists.
*
* @package environmentcheck
*/
class HasClassCheck implements EnvironmentCheck
{
@ -26,7 +25,7 @@ class HasClassCheck implements EnvironmentCheck
}
/**
* @inheritdoc
* {@inheritDoc}
*
* @return array
*/
@ -34,8 +33,7 @@ class HasClassCheck implements EnvironmentCheck
{
if (class_exists($this->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');
}
}

View File

@ -2,13 +2,12 @@
namespace SilverStripe\EnvironmentCheck\Checks;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
/**
* Check that the given function exists.
*
* @package environmentcheck
*/
class HasFunctionCheck implements EnvironmentCheck
{
@ -26,16 +25,15 @@ class HasFunctionCheck implements EnvironmentCheck
}
/**
* @inheritdoc
* {@inheritDoc}
*
* @return array
*/
public function check()
{
if (function_exists($this->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');
}
}

View File

@ -2,15 +2,14 @@
namespace SilverStripe\EnvironmentCheck\Checks;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
/**
* Checks if the SMTP connection configured through PHP.ini works as expected.
*
* Only checks socket connection with HELO command, not actually sending the email.
*
* @package environmentcheck
*/
class SMTPConnectCheck implements EnvironmentCheck
{
@ -42,7 +41,7 @@ class SMTPConnectCheck implements EnvironmentCheck
if (!$this->host) {
$this->host = 'localhost';
}
$this->port = ($port) ? $port : ini_get('smtp_port');
if (!$this->port) {
$this->port = 25;
@ -52,7 +51,7 @@ class SMTPConnectCheck implements EnvironmentCheck
}
/**
* @inheritdoc
* {@inheritDoc}
*
* @return array
*/
@ -71,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)
);
}

View File

@ -2,16 +2,14 @@
namespace SilverStripe\EnvironmentCheck\Checks;
use Solr;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
/**
* Check the availability of all Solr indexes of given class.
*
* If there are no indexes of given class found, the returned status will still be "OK".
*
* @package environmentcheck
*/
class SolrIndexCheck implements EnvironmentCheck
{
@ -29,7 +27,7 @@ class SolrIndexCheck implements EnvironmentCheck
}
/**
* @inheritdoc
* {@inheritDoc}
*
* @return array
*/
@ -37,15 +35,18 @@ class SolrIndexCheck implements EnvironmentCheck
{
$brokenCores = array();
if (!class_exists('Solr')) {
/**
* @todo Revisit this when silverstripe/fulltextsearch has 4.x compat
*/
if (!class_exists('\\Solr')) {
return array(
EnvironmentCheck::ERROR,
'Class `Solr` not found. Is the fulltextsearch module installed?'
);
}
$service = Solr::service();
foreach (Solr::get_indexes($this->indexClass) as $index) {
$service = \Solr::service();
foreach (\Solr::get_indexes($this->indexClass) as $index) {
$core = $index->getIndexName();
if (!$service->coreIsActive($core)) {
$brokenCores[] = $core;

View File

@ -2,17 +2,15 @@
namespace SilverStripe\EnvironmentCheck\Checks;
use SilverStripe\Control\Director;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
/**
* Check that a given URL is functioning, by default, the homepage.
*
*
* Note that Director::test() will be used rather than a CURL check.
*
* @package environmentcheck
*/
class URLCheck implements EnvironmentCheck
{
@ -25,7 +23,7 @@ class URLCheck implements EnvironmentCheck
* @var string
*/
protected $testString;
/*
* @param string $url The URL to check, relative to the site (homepage is '').
* @param string $testString An optional piece of text to search for on the homepage.
@ -37,11 +35,10 @@ class URLCheck implements EnvironmentCheck
}
/**
* @inheritdoc
* {@inheritDoc}
*
* @return array
*
* @throws SS_HTTPResponse_Exception
* @throws HTTPResponse_Exception
*/
public function check()
{
@ -57,11 +54,10 @@ class URLCheck implements EnvironmentCheck
EnvironmentCheck::WARNING,
sprintf('Success retrieving "%s", but string "%s" not found', $this->url, $this->testString)
);
} else {
return array(
EnvironmentCheck::OK,
sprintf('Success retrieving "%s"', $this->url)
);
}
return array(
EnvironmentCheck::OK,
sprintf('Success retrieving "%s"', $this->url)
);
}
}

View File

@ -2,13 +2,14 @@
namespace SilverStripe\EnvironmentCheck\Controllers;
use SilverStripe\EnvironmentCheck\EnvironmentChecker;
use SilverStripe\Control\Controller;
use SilverStripe\EnvironmentCheck\EnvironmentChecker;
/**
* Class DevCheckController
*
* @package environmentcheck
*/
class DevCheckController extends Controller
{
/**
@ -26,11 +27,11 @@ class DevCheckController extends Controller
private static $permission = 'ADMIN';
/**
* @param SS_HTTPRequest $request
* @param HTTPRequest $request
*
* @return EnvironmentChecker
*
* @throws SS_HTTPResponse_Exception
* @throws HTTPResponse_Exception
*/
public function index($request)
{

View File

@ -2,13 +2,14 @@
namespace SilverStripe\EnvironmentCheck\Controllers;
use SilverStripe\EnvironmentCheck\EnvironmentChecker;
use SilverStripe\Control\Controller;
use SilverStripe\EnvironmentCheck\EnvironmentChecker;
/**
* Class DevHealthController
*
* @package environmentcheck
*/
class DevHealthController extends Controller
{
/**
@ -21,7 +22,7 @@ class DevHealthController extends Controller
/**
* @return EnvironmentChecker
*
* @throws SS_HTTPResponse_Exception
* @throws HTTPResponse_Exception
*/
public function index()
{

View File

@ -2,22 +2,21 @@
namespace SilverStripe\EnvironmentCheck;
/**
* Interface for environment checks
*
*
* An environment check is a test that can be performed on a live environment. They differ from
* unit tests in that they are designed to check the state of the environment/server, rather than
* the code.
*
*
* Environment checks should *never* alter production data.
*
*
* Some things you might make environment checks for:
* - Can I access the database?
* - Are the right PHP modules installed?
* - Are the file permissions correct?
*
* @package environmentcheck
*/
interface EnvironmentCheck
{

View File

@ -2,21 +2,14 @@
namespace SilverStripe\EnvironmentCheck;
use InvalidArgumentException;
use Exception;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use InvalidArgumentException;
use SilverStripe\Core\Object;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\ORM\ArrayList;
use SilverStripe\View\ArrayData;
use SilverStripe\View\ViewableData;
/**
* Represents a suite of environment checks.
* Specific checks can be registered against a named instance of EnvironmentCheckSuite.
@ -35,6 +28,8 @@ use SilverStripe\View\ViewableData;
* - mycheck
*
* $result = EnvironmentCheckSuite::inst('health')->run();
*
* @package environmentcheck
*/
class EnvironmentCheckSuite extends Object
{
@ -94,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']);
}
@ -131,6 +126,7 @@ class EnvironmentCheckSuite extends Object
* Get instances of all the environment checks.
*
* @return array
* @throws InvalidArgumentException
*/
protected function checkInstances()
{
@ -142,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);
@ -214,106 +212,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'");
}
}
}

View File

@ -0,0 +1,125 @@
<?php
namespace SilverStripe\EnvironmentCheck;
use InvalidArgumentException;
use SilverStripe\ORM\ArrayList;
use SilverStripe\View\ArrayData;
use SilverStripe\View\ViewableData;
/**
* A single set of results from running an EnvironmentCheckSuite
*
* @package environmentcheck
*/
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.
*
* @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;
}
}
}

View File

@ -2,37 +2,25 @@
namespace SilverStripe\EnvironmentCheck;
use Psr\Log\LogLevel;
use SilverStripe\Control\Director;
use SilverStripe\Control\Email\Email;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Security\Member;
use SilverStripe\Security\BasicAuth;
use SilverStripe\Control\Director;
use SilverStripe\Security\Permission;
use SilverStripe\EnvironmentCheck\EnvironmentCheckSuite;
use SilverStripe\Control\Email\Email;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\Logging\Log;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Core\Config\Config;
use SilverStripe\Control\RequestHandler;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\Deprecation;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\EnvironmentCheck\EnvironmentCheckSuite;
use SilverStripe\Security\BasicAuth;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
/**
* Provides an interface for checking the given EnvironmentCheckSuite.
*
* @package environmentcheck
*/
class EnvironmentChecker extends RequestHandler
{
@ -74,24 +62,24 @@ class EnvironmentChecker extends RequestHandler
private static $email_results = false;
/**
* @var bool Log results via {@link SS_Log}
* @var bool Log results via {@link \Psr\Log\LoggerInterface}
*/
private static $log_results_warning = false;
/**
* @var int Maps to {@link Zend_Log} levels. Defaults to Zend_Log::WARN
* @var string Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::WARNING
*/
private static $log_results_warning_level = 4;
private static $log_results_warning_level = LogLevel::WARNING;
/**
* @var bool Log results via {@link SS_Log}
* @var bool Log results via a {@link \Psr\Log\LoggerInterface}
*/
private static $log_results_error = false;
/**
* @var int Maps to {@link Zend_Log} levels. Defaults to Zend_Log::ALERT
* @var int Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::ALERT
*/
private static $log_results_error_level = 1;
private static $log_results_error_level = LogLevel::ALERT;
/**
* @param string $checkSuiteName
@ -100,7 +88,7 @@ class EnvironmentChecker extends RequestHandler
public function __construct($checkSuiteName, $title)
{
parent::__construct();
$this->checkSuiteName = $checkSuiteName;
$this->title = $title;
}
@ -108,7 +96,7 @@ class EnvironmentChecker extends RequestHandler
/**
* @param string $permission
*
* @throws SS_HTTPResponse_Exception
* @throws HTTPResponse_Exception
*/
public function init($permission = 'ADMIN')
{
@ -116,8 +104,7 @@ 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
)
@ -150,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();
@ -164,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)
@ -180,16 +166,15 @@ 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()
{
@ -201,14 +186,19 @@ class EnvironmentChecker extends RequestHandler
}
$resultText = $result->customise(array(
"URL" => Director::absoluteBaseURL(),
"Title" => $this->title,
"Name" => $this->checkSuiteName,
"ErrorCode" => $this->errorCode,
))->renderWith("SilverStripe\\EnvironmentCheck\\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();
}
@ -228,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());
@ -238,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)
{
Log::log($message, $level);
Injector::inst()->get('Logger')->log($level, $message);
}
/**
@ -268,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('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'from_email_address', $from);
Config::inst()->update(__CLASS__, 'from_email_address', $from);
}
/**
@ -278,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('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'from_email_address');
return Config::inst()->get(__CLASS__, 'from_email_address');
}
/**
@ -288,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('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'to_email_address', $to);
Config::inst()->update(__CLASS__, 'to_email_address', $to);
}
/**
@ -298,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('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'to_email_address');
return Config::inst()->get(__CLASS__, 'to_email_address');
}
/**
@ -308,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('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'email_results', $results);
Config::inst()->update(__CLASS__, 'email_results', $results);
}
/**
@ -318,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('SilverStripe\\EnvironmentCheck\\EnvironmentChecker', 'email_results');
return Config::inst()->get(__CLASS__, 'email_results');
}
}

View File

@ -2,17 +2,17 @@
namespace SilverStripe\EnvironmentCheck\Tests\Checks;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\EnvironmentCheck\Checks\DatabaseCheck;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Security\Member;
/**
* Class DatabaseCheckTest
*
* @mixin PHPUnit_Framework_TestCase
*
* @package environmentcheck
*/
class DatabaseCheckTest extends SapphireTest
{
@ -22,7 +22,7 @@ class DatabaseCheckTest extends SapphireTest
$expected = array(
EnvironmentCheck::OK,
'',
''
);
$this->assertEquals($expected, $check->check());

View File

@ -2,17 +2,16 @@
namespace SilverStripe\EnvironmentCheck\Tests\Checks;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\EnvironmentCheck\Checks\ExternalURLCheck;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\Dev\SapphireTest;
/**
* Class ExternalURLCheckTest
*
* @mixin PHPUnit_Framework_TestCase
*
* @package environmentcheck
*/
class ExternalURLCheckTest extends SapphireTest
{
@ -24,7 +23,7 @@ class ExternalURLCheckTest extends SapphireTest
$expected = array(
EnvironmentCheck::ERROR,
'Success retrieving "http://missing-site/" (Code: 404)',
'Success retrieving "http://missing-site/" (Code: 404)'
);
$this->assertEquals($expected, $check->check());

View File

@ -2,17 +2,16 @@
namespace SilverStripe\EnvironmentCheck\Tests\Checks;
use SilverStripe\EnvironmentCheck\Checks\FileWriteableCheck;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\Dev\SapphireTest;
/**
* Class FileWritableCheckTest
*
* @mixin PHPUnit_Framework_TestCase
*
* @package environmentcheck
*/
class FileWritableCheckTest extends SapphireTest
{
@ -22,7 +21,7 @@ class FileWritableCheckTest extends SapphireTest
$expected = array(
EnvironmentCheck::OK,
'',
''
);
$this->assertEquals($expected, $check->check());

View File

@ -2,17 +2,16 @@
namespace SilverStripe\EnvironmentCheck\Tests\Checks;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\EnvironmentCheck\Checks\HasClassCheck;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\Dev\SapphireTest;
/**
* Class HasClassCheckTest
*
* @mixin PHPUnit_Framework_TestCase
*
* @package environmentcheck
*/
class HasClassCheckTest extends SapphireTest
{
@ -22,7 +21,7 @@ class HasClassCheckTest extends SapphireTest
$expected = array(
EnvironmentCheck::ERROR,
'Class foo doesn\'t exist',
'Class foo doesn\'t exist'
);
$this->assertEquals($expected, $check->check());

View File

@ -2,17 +2,16 @@
namespace SilverStripe\EnvironmentCheck\Tests\Checks;
use SilverStripe\EnvironmentCheck\Checks\HasFunctionCheck;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\Dev\SapphireTest;
/**
* Class HasFunctionCheckTest
*
* @mixin PHPUnit_Framework_TestCase
*
* @package environmentcheck
*/
class HasFunctionCheckTest extends SapphireTest
{
@ -22,7 +21,7 @@ class HasFunctionCheckTest extends SapphireTest
$expected = array(
EnvironmentCheck::ERROR,
'foo() doesn\'t exist',
'foo() doesn\'t exist'
);
$this->assertEquals($expected, $check->check());
@ -34,7 +33,7 @@ class HasFunctionCheckTest extends SapphireTest
$expected = array(
EnvironmentCheck::OK,
'class_exists() exists',
'class_exists() exists'
);
$this->assertEquals($expected, $check->check());

View File

@ -2,17 +2,16 @@
namespace SilverStripe\EnvironmentCheck\Tests\Checks;
use SilverStripe\EnvironmentCheck\Checks\URLCheck;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\Dev\SapphireTest;
/**
* Class URLCheckTest
*
* @mixin PHPUnit_Framework_TestCase
*
* @package environmentcheck
*/
class URLCheckTest extends SapphireTest
{
@ -22,7 +21,7 @@ class URLCheckTest extends SapphireTest
$expected = array(
EnvironmentCheck::ERROR,
'Error retrieving "foo" (Code: 404)',
'Error retrieving "foo" (Code: 404)'
);
$this->assertEquals($expected, $check->check());

View File

@ -2,22 +2,25 @@
namespace SilverStripe\EnvironmentCheck\Tests\Controllers;
use SilverStripe\EnvironmentCheck\Controllers\DevCheckController;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\EnvironmentCheck\Controllers\DevCheckController;
/**
* Class DevCheckControllerTest
*
* @mixin PHPUnit_Framework_TestCase
*
* @package environmentcheck
*/
class DevCheckControllerTest extends SapphireTest
{
/**
* {@inheritDoc}
* @var array
*/
protected $usesDatabase = true;
public function testIndexCreatesChecker()
{
$controller = new DevCheckController();

View File

@ -2,22 +2,25 @@
namespace SilverStripe\EnvironmentCheck\Tests\Controllers;
use SilverStripe\EnvironmentCheck\Controllers\DevHealthController;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\EnvironmentCheck\Controllers\DevHealthController;
/**
* Class DevHealthControllerTest
*
* @mixin PHPUnit_Framework_TestCase
*
* @package environmentcheck
*/
class DevHealthControllerTest extends SapphireTest
{
/**
* {@inheritDoc}
* @var array
*/
protected $usesDatabase = true;
public function testIndexCreatesChecker()
{
$controller = new DevHealthController();

View File

@ -2,30 +2,46 @@
namespace SilverStripe\EnvironmentCheck\Tests;
use Phockito;
use SilverStripe\Core\Config\Config;
use SilverStripe\EnvironmentCheck\EnvironmentCheckSuite;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\Dev\TestOnly;
use SilverStripe\EnvironmentCheck\EnvironmentCheck;
use SilverStripe\EnvironmentCheck\EnvironmentCheckSuite;
/**
* Class EnvironmentCheckerTest
*
* @package environmentcheck
*/
class EnvironmentCheckerTest extends SapphireTest
{
/**
* {@inheritDoc}
* @var bool
*/
protected $usesDatabase = true;
/**
* {@inheritDoc}
*/
public function setUpOnce()
{
parent::setUpOnce();
Phockito::include_hamcrest();
$logger = Injector::inst()->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();
@ -33,6 +49,9 @@ class EnvironmentCheckerTest extends SapphireTest
Config::nest();
}
/**
* {@inheritDoc}
*/
public function tearDown()
{
Config::unnest();
@ -105,7 +124,7 @@ class EnvironmentCheckerTest_CheckWarnings implements EnvironmentCheck, TestOnly
{
public function check()
{
return array(EnvironmentCheck::WARNING, "test warning");
return array(EnvironmentCheck::WARNING, 'test warning');
}
}
@ -113,6 +132,6 @@ class EnvironmentCheckerTest_CheckErrors implements EnvironmentCheck, TestOnly
{
public function check()
{
return array(EnvironmentCheck::ERROR, "test error");
return array(EnvironmentCheck::ERROR, 'test error');
}
}