Completed
Branch master (9dcfc4)
by Daniel
24:32
created
src/EnvironmentCheckSuite.php 1 patch
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -36,185 +36,185 @@
 block discarded – undo
36 36
  */
37 37
 class EnvironmentCheckSuite
38 38
 {
39
-    use Configurable;
40
-    use Injectable;
41
-    use Extensible;
42
-    /**
43
-     * Name of this suite.
44
-     *
45
-     * @var string
46
-     */
47
-    protected $name;
48
-
49
-    /**
50
-     * @var array
51
-     */
52
-    protected $checks = [];
53
-
54
-    /**
55
-     * Associative array of named checks registered via the config system. Each check should specify:
56
-     * - definition (e.g. 'MyHealthCheck("my param")')
57
-     * - title (e.g. 'Is my feature working?')
58
-     * - state (setting this to 'disabled' will cause suites to skip this check entirely.
59
-     *
60
-     * @var array
61
-     */
62
-    private static $registered_checks = [];
63
-
64
-    /**
65
-     * Associative array of named suites registered via the config system. Each suite should enumerate
66
-     * named checks that have been configured in 'registered_checks'.
67
-     *
68
-     * @var array
69
-     */
70
-    private static $registered_suites = [];
71
-
72
-    /**
73
-     * Load checks for this suite from the configuration system. This is an alternative to the
74
-     * EnvironmentCheckSuite::register - both can be used, checks will be appended to the suite.
75
-     *
76
-     * @param string $suiteName The name of this suite.
77
-     */
78
-    public function __construct($suiteName)
79
-    {
80
-        $this->constructExtensions();
81
-        if (empty($this->config()->registered_suites[$suiteName])) {
82
-            // Not registered via config system, but it still may be configured later via self::register.
83
-            return;
84
-        }
85
-
86
-        foreach ($this->config()->registered_suites[$suiteName] as $checkName) {
87
-            if (empty($this->config()->registered_checks[$checkName])) {
88
-                throw new InvalidArgumentException(
89
-                    "Bad EnvironmentCheck: '$checkName' - the named check has not been registered."
90
-                );
91
-            }
92
-
93
-            $check = $this->config()->registered_checks[$checkName];
94
-
95
-            // Existing named checks can be disabled by setting their 'state' to 'disabled'.
96
-            // This is handy for disabling checks mandated by modules.
97
-            if (!empty($check['state']) && $check['state'] === 'disabled') {
98
-                continue;
99
-            }
100
-
101
-            // Add the check to this suite.
102
-            $this->push($check['definition'], $check['title']);
103
-        }
104
-    }
105
-
106
-    /**
107
-     * Run this test suite and return the result code of the worst result.
108
-     *
109
-     * @return int
110
-     */
111
-    public function run()
112
-    {
113
-        $result = new EnvironmentCheckSuiteResult();
114
-
115
-        foreach ($this->checkInstances() as $check) {
116
-            list($checkClass, $checkTitle) = $check;
117
-            try {
118
-                list($status, $message) = $checkClass->check();
119
-            // If the check fails, register that as an error
120
-            } catch (Exception $e) {
121
-                $status = EnvironmentCheck::ERROR;
122
-                $message = $e->getMessage();
123
-            }
124
-            $result->addResult($status, $message, $checkTitle);
125
-        }
126
-
127
-        return $result;
128
-    }
129
-
130
-    /**
131
-     * Get instances of all the environment checks.
132
-     *
133
-     * @return array
134
-     * @throws InvalidArgumentException
135
-     */
136
-    protected function checkInstances()
137
-    {
138
-        $output = [];
139
-        foreach ($this->checks as $check) {
140
-            list($checkClass, $checkTitle) = $check;
141
-            if (is_string($checkClass)) {
142
-                $checkInst = Injector::inst()->create($checkClass);
143
-                if ($checkInst instanceof EnvironmentCheck) {
144
-                    $output[] = [$checkInst, $checkTitle];
145
-                } else {
146
-                    throw new InvalidArgumentException(
147
-                        "Bad EnvironmentCheck: '$checkClass' - the named class doesn't implement EnvironmentCheck"
148
-                    );
149
-                }
150
-            } elseif ($checkClass instanceof EnvironmentCheck) {
151
-                $output[] = [$checkClass, $checkTitle];
152
-            } else {
153
-                throw new InvalidArgumentException("Bad EnvironmentCheck: " . var_export($check, true));
154
-            }
155
-        }
156
-        return $output;
157
-    }
158
-
159
-    /**
160
-     * Add a check to this suite.
161
-     *
162
-     * @param mixed $check
163
-     * @param string $title
164
-     */
165
-    public function push($check, $title = null)
166
-    {
167
-        if (!$title) {
168
-            $title = is_string($check) ? $check : get_class($check);
169
-        }
170
-        $this->checks[] = [$check, $title];
171
-    }
172
-
173
-    /////////////////////////////////////////////////////////////////////////////////////////////
174
-
175
-    /**
176
-     * @var array
177
-     */
178
-    protected static $instances = [];
179
-
180
-    /**
181
-     * Return a named instance of EnvironmentCheckSuite.
182
-     *
183
-     * @param string $name
184
-     *
185
-     * @return EnvironmentCheckSuite
186
-     */
187
-    public static function inst($name)
188
-    {
189
-        if (!isset(self::$instances[$name])) {
190
-            self::$instances[$name] = new EnvironmentCheckSuite($name);
191
-        }
192
-        return self::$instances[$name];
193
-    }
194
-
195
-    /**
196
-     * Register a check against the named check suite.
197
-     *
198
-     * @param string|array $names
199
-     * @param EnvironmentCheck $check
200
-     * @param string|array
201
-     */
202
-    public static function register($names, $check, $title = null)
203
-    {
204
-        if (!is_array($names)) {
205
-            $names = [$names];
206
-        }
207
-
208
-        foreach ($names as $name) {
209
-            self::inst($name)->push($check, $title);
210
-        }
211
-    }
212
-
213
-    /**
214
-     * Unregisters all checks.
215
-     */
216
-    public static function reset()
217
-    {
218
-        self::$instances = [];
219
-    }
39
+	use Configurable;
40
+	use Injectable;
41
+	use Extensible;
42
+	/**
43
+	 * Name of this suite.
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $name;
48
+
49
+	/**
50
+	 * @var array
51
+	 */
52
+	protected $checks = [];
53
+
54
+	/**
55
+	 * Associative array of named checks registered via the config system. Each check should specify:
56
+	 * - definition (e.g. 'MyHealthCheck("my param")')
57
+	 * - title (e.g. 'Is my feature working?')
58
+	 * - state (setting this to 'disabled' will cause suites to skip this check entirely.
59
+	 *
60
+	 * @var array
61
+	 */
62
+	private static $registered_checks = [];
63
+
64
+	/**
65
+	 * Associative array of named suites registered via the config system. Each suite should enumerate
66
+	 * named checks that have been configured in 'registered_checks'.
67
+	 *
68
+	 * @var array
69
+	 */
70
+	private static $registered_suites = [];
71
+
72
+	/**
73
+	 * Load checks for this suite from the configuration system. This is an alternative to the
74
+	 * EnvironmentCheckSuite::register - both can be used, checks will be appended to the suite.
75
+	 *
76
+	 * @param string $suiteName The name of this suite.
77
+	 */
78
+	public function __construct($suiteName)
79
+	{
80
+		$this->constructExtensions();
81
+		if (empty($this->config()->registered_suites[$suiteName])) {
82
+			// Not registered via config system, but it still may be configured later via self::register.
83
+			return;
84
+		}
85
+
86
+		foreach ($this->config()->registered_suites[$suiteName] as $checkName) {
87
+			if (empty($this->config()->registered_checks[$checkName])) {
88
+				throw new InvalidArgumentException(
89
+					"Bad EnvironmentCheck: '$checkName' - the named check has not been registered."
90
+				);
91
+			}
92
+
93
+			$check = $this->config()->registered_checks[$checkName];
94
+
95
+			// Existing named checks can be disabled by setting their 'state' to 'disabled'.
96
+			// This is handy for disabling checks mandated by modules.
97
+			if (!empty($check['state']) && $check['state'] === 'disabled') {
98
+				continue;
99
+			}
100
+
101
+			// Add the check to this suite.
102
+			$this->push($check['definition'], $check['title']);
103
+		}
104
+	}
105
+
106
+	/**
107
+	 * Run this test suite and return the result code of the worst result.
108
+	 *
109
+	 * @return int
110
+	 */
111
+	public function run()
112
+	{
113
+		$result = new EnvironmentCheckSuiteResult();
114
+
115
+		foreach ($this->checkInstances() as $check) {
116
+			list($checkClass, $checkTitle) = $check;
117
+			try {
118
+				list($status, $message) = $checkClass->check();
119
+			// If the check fails, register that as an error
120
+			} catch (Exception $e) {
121
+				$status = EnvironmentCheck::ERROR;
122
+				$message = $e->getMessage();
123
+			}
124
+			$result->addResult($status, $message, $checkTitle);
125
+		}
126
+
127
+		return $result;
128
+	}
129
+
130
+	/**
131
+	 * Get instances of all the environment checks.
132
+	 *
133
+	 * @return array
134
+	 * @throws InvalidArgumentException
135
+	 */
136
+	protected function checkInstances()
137
+	{
138
+		$output = [];
139
+		foreach ($this->checks as $check) {
140
+			list($checkClass, $checkTitle) = $check;
141
+			if (is_string($checkClass)) {
142
+				$checkInst = Injector::inst()->create($checkClass);
143
+				if ($checkInst instanceof EnvironmentCheck) {
144
+					$output[] = [$checkInst, $checkTitle];
145
+				} else {
146
+					throw new InvalidArgumentException(
147
+						"Bad EnvironmentCheck: '$checkClass' - the named class doesn't implement EnvironmentCheck"
148
+					);
149
+				}
150
+			} elseif ($checkClass instanceof EnvironmentCheck) {
151
+				$output[] = [$checkClass, $checkTitle];
152
+			} else {
153
+				throw new InvalidArgumentException("Bad EnvironmentCheck: " . var_export($check, true));
154
+			}
155
+		}
156
+		return $output;
157
+	}
158
+
159
+	/**
160
+	 * Add a check to this suite.
161
+	 *
162
+	 * @param mixed $check
163
+	 * @param string $title
164
+	 */
165
+	public function push($check, $title = null)
166
+	{
167
+		if (!$title) {
168
+			$title = is_string($check) ? $check : get_class($check);
169
+		}
170
+		$this->checks[] = [$check, $title];
171
+	}
172
+
173
+	/////////////////////////////////////////////////////////////////////////////////////////////
174
+
175
+	/**
176
+	 * @var array
177
+	 */
178
+	protected static $instances = [];
179
+
180
+	/**
181
+	 * Return a named instance of EnvironmentCheckSuite.
182
+	 *
183
+	 * @param string $name
184
+	 *
185
+	 * @return EnvironmentCheckSuite
186
+	 */
187
+	public static function inst($name)
188
+	{
189
+		if (!isset(self::$instances[$name])) {
190
+			self::$instances[$name] = new EnvironmentCheckSuite($name);
191
+		}
192
+		return self::$instances[$name];
193
+	}
194
+
195
+	/**
196
+	 * Register a check against the named check suite.
197
+	 *
198
+	 * @param string|array $names
199
+	 * @param EnvironmentCheck $check
200
+	 * @param string|array
201
+	 */
202
+	public static function register($names, $check, $title = null)
203
+	{
204
+		if (!is_array($names)) {
205
+			$names = [$names];
206
+		}
207
+
208
+		foreach ($names as $name) {
209
+			self::inst($name)->push($check, $title);
210
+		}
211
+	}
212
+
213
+	/**
214
+	 * Unregisters all checks.
215
+	 */
216
+	public static function reset()
217
+	{
218
+		self::$instances = [];
219
+	}
220 220
 }
Please login to merge, or discard this patch.
src/Controllers/DevHealthController.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -12,25 +12,25 @@
 block discarded – undo
12 12
  */
13 13
 class DevHealthController extends Controller
14 14
 {
15
-    /**
16
-     * @var array
17
-     */
18
-    private static $allowed_actions = [
19
-        'index'
20
-    ];
15
+	/**
16
+	 * @var array
17
+	 */
18
+	private static $allowed_actions = [
19
+		'index'
20
+	];
21 21
 
22
-    /**
23
-     * @return EnvironmentChecker
24
-     *
25
-     * @throws HTTPResponse_Exception
26
-     */
27
-    public function index()
28
-    {
29
-        // health check does not require permission to run
22
+	/**
23
+	 * @return EnvironmentChecker
24
+	 *
25
+	 * @throws HTTPResponse_Exception
26
+	 */
27
+	public function index()
28
+	{
29
+		// health check does not require permission to run
30 30
 
31
-        $checker = new EnvironmentChecker('health', 'Site health');
32
-        $checker->setErrorCode(500);
31
+		$checker = new EnvironmentChecker('health', 'Site health');
32
+		$checker->setErrorCode(500);
33 33
 
34
-        return $checker;
35
-    }
34
+		return $checker;
35
+	}
36 36
 }
Please login to merge, or discard this patch.
src/Controllers/DevCheckController.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -12,38 +12,38 @@
 block discarded – undo
12 12
  */
13 13
 class DevCheckController extends Controller
14 14
 {
15
-    /**
16
-     * @var array
17
-     */
18
-    private static $allowed_actions = [
19
-        'index'
20
-    ];
21
-
22
-    /**
23
-     * Permission code to check for access to this controller.
24
-     *
25
-     * @var string
26
-     */
27
-    private static $permission = 'ADMIN';
28
-
29
-    /**
30
-     * @param HTTPRequest $request
31
-     *
32
-     * @return EnvironmentChecker
33
-     *
34
-     * @throws HTTPResponse_Exception
35
-     */
36
-    public function index($request)
37
-    {
38
-        $suite = 'check';
39
-
40
-        if ($name = $request->param('Suite')) {
41
-            $suite = $name;
42
-        }
43
-
44
-        $checker = new EnvironmentChecker($suite, 'Environment status');
45
-        $checker->init($this->config()->permission);
46
-
47
-        return $checker;
48
-    }
15
+	/**
16
+	 * @var array
17
+	 */
18
+	private static $allowed_actions = [
19
+		'index'
20
+	];
21
+
22
+	/**
23
+	 * Permission code to check for access to this controller.
24
+	 *
25
+	 * @var string
26
+	 */
27
+	private static $permission = 'ADMIN';
28
+
29
+	/**
30
+	 * @param HTTPRequest $request
31
+	 *
32
+	 * @return EnvironmentChecker
33
+	 *
34
+	 * @throws HTTPResponse_Exception
35
+	 */
36
+	public function index($request)
37
+	{
38
+		$suite = 'check';
39
+
40
+		if ($name = $request->param('Suite')) {
41
+			$suite = $name;
42
+		}
43
+
44
+		$checker = new EnvironmentChecker($suite, 'Environment status');
45
+		$checker->init($this->config()->permission);
46
+
47
+		return $checker;
48
+	}
49 49
 }
Please login to merge, or discard this patch.
src/EnvironmentChecker.php 1 patch
Indentation   +287 added lines, -287 removed lines patch added patch discarded remove patch
@@ -25,291 +25,291 @@
 block discarded – undo
25 25
  */
26 26
 class EnvironmentChecker extends RequestHandler
27 27
 {
28
-    /**
29
-     * @var array
30
-     */
31
-    private static $url_handlers = [
32
-        '' => 'index',
33
-    ];
34
-
35
-    /**
36
-     * @var string
37
-     */
38
-    protected $checkSuiteName;
39
-
40
-    /**
41
-     * @var string
42
-     */
43
-    protected $title;
44
-
45
-    /**
46
-     * @var int
47
-     */
48
-    protected $errorCode = 500;
49
-
50
-    /**
51
-     * @var null|string
52
-     */
53
-    private static $to_email_address = null;
54
-
55
-    /**
56
-     * @var null|string
57
-     */
58
-    private static $from_email_address = null;
59
-
60
-    /**
61
-     * @var bool
62
-     */
63
-    private static $email_results = false;
64
-
65
-    /**
66
-     * @var bool Log results via {@link \Psr\Log\LoggerInterface}
67
-     */
68
-    private static $log_results_warning = false;
69
-
70
-    /**
71
-     * @var string Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::WARNING
72
-     */
73
-    private static $log_results_warning_level = LogLevel::WARNING;
74
-
75
-    /**
76
-     * @var bool Log results via a {@link \Psr\Log\LoggerInterface}
77
-     */
78
-    private static $log_results_error = false;
79
-
80
-    /**
81
-     * @var int Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::ALERT
82
-     */
83
-    private static $log_results_error_level = LogLevel::ALERT;
84
-
85
-    /**
86
-     * @param string $checkSuiteName
87
-     * @param string $title
88
-     */
89
-    public function __construct($checkSuiteName, $title)
90
-    {
91
-        parent::__construct();
92
-
93
-        $this->checkSuiteName = $checkSuiteName;
94
-        $this->title = $title;
95
-    }
96
-
97
-    /**
98
-     * @param string $permission
99
-     *
100
-     * @throws HTTPResponse_Exception
101
-     */
102
-    public function init($permission = 'ADMIN')
103
-    {
104
-        // if the environment supports it, provide a basic auth challenge and see if it matches configured credentials
105
-        if (getenv('ENVCHECK_BASICAUTH_USERNAME') && getenv('ENVCHECK_BASICAUTH_PASSWORD')) {
106
-            if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
107
-                // authenticate the input user/pass with the configured credentials
108
-                if (!(
109
-                        $_SERVER['PHP_AUTH_USER'] == getenv('ENVCHECK_BASICAUTH_USERNAME')
110
-                        && $_SERVER['PHP_AUTH_PW'] == getenv('ENVCHECK_BASICAUTH_PASSWORD')
111
-                    )
112
-                ) {
113
-                    $response = new HTTPResponse(null, 401);
114
-                    $response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
115
-                    // Exception is caught by RequestHandler->handleRequest() and will halt further execution
116
-                    $e = new HTTPResponse_Exception(null, 401);
117
-                    $e->setResponse($response);
118
-                    throw $e;
119
-                }
120
-            } else {
121
-                $response = new HTTPResponse(null, 401);
122
-                $response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
123
-                // Exception is caught by RequestHandler->handleRequest() and will halt further execution
124
-                $e = new HTTPResponse_Exception(null, 401);
125
-                $e->setResponse($response);
126
-                throw $e;
127
-            }
128
-        } else {
129
-            if (!$this->canAccess(null, $permission)) {
130
-                return $this->httpError(403);
131
-            }
132
-        }
133
-    }
134
-
135
-    /**
136
-     * @param null|int|Member $member
137
-     * @param string $permission
138
-     *
139
-     * @return bool
140
-     *
141
-     * @throws HTTPResponse_Exception
142
-     */
143
-    public function canAccess($member = null, $permission = 'ADMIN')
144
-    {
145
-        if (!$member) {
146
-            $member = Member::currentUser();
147
-        }
148
-
149
-        if (!$member) {
150
-            $member = BasicAuth::requireLogin('Environment Checker', $permission, false);
151
-        }
152
-
153
-        // We allow access to this controller regardless of live-status or ADMIN permission only
154
-        // if on CLI.  Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
155
-        if (Director::isDev()
156
-            || Director::is_cli()
157
-            || empty($permission)
158
-            || Permission::checkMember($member, $permission)
159
-        ) {
160
-            return true;
161
-        }
162
-
163
-        // Extended access checks.
164
-        // "Veto" style, return NULL to abstain vote.
165
-        $canExtended = null;
166
-        $results = $this->extend('canAccess', $member);
167
-        if ($results && is_array($results)) {
168
-            if (!min($results)) {
169
-                return false;
170
-            }
171
-            return true;
172
-        }
173
-
174
-        return false;
175
-    }
176
-
177
-    /**
178
-     * @return HTTPResponse
179
-     */
180
-    public function index()
181
-    {
182
-        $response = new HTTPResponse;
183
-        $result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run();
184
-
185
-        if (!$result->ShouldPass()) {
186
-            $response->setStatusCode($this->errorCode);
187
-        }
188
-
189
-        $resultText = $result->customise([
190
-            'URL' => Director::absoluteBaseURL(),
191
-            'Title' => $this->title,
192
-            'Name' => $this->checkSuiteName,
193
-            'ErrorCode' => $this->errorCode,
194
-        ])->renderWith(__CLASS__);
195
-
196
-        if ($this->config()->email_results && !$result->ShouldPass()) {
197
-            $email = new Email(
198
-                $this->config()->from_email_address,
199
-                $this->config()->to_email_address,
200
-                $this->title,
201
-                $resultText
202
-            );
203
-            $email->send();
204
-        }
205
-
206
-        // Optionally log errors and warnings individually
207
-        foreach ($result->Details() as $detail) {
208
-            if ($this->config()->log_results_warning && $detail->StatusCode == EnvironmentCheck::WARNING) {
209
-                $this->log(
210
-                    sprintf('EnvironmentChecker warning at "%s" check. Message: %s', $detail->Check, $detail->Message),
211
-                    $this->config()->log_results_warning_level
212
-                );
213
-            } elseif ($this->config()->log_results_error && $detail->StatusCode == EnvironmentCheck::ERROR) {
214
-                $this->log(
215
-                    sprintf('EnvironmentChecker error at "%s" check. Message: %s', $detail->Check, $detail->Message),
216
-                    $this->config()->log_results_error_level
217
-                );
218
-            }
219
-        }
220
-
221
-        // output the result as JSON if requested
222
-        if ($this->getRequest()->getExtension() == 'json'
223
-            || strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false
224
-        ) {
225
-            $response->setBody($result->toJSON());
226
-            $response->addHeader('Content-Type', 'application/json');
227
-            return $response;
228
-        }
229
-
230
-        $response->setBody($resultText);
231
-
232
-        return $response;
233
-    }
234
-
235
-    /**
236
-     * Sends a log entry to the configured PSR-3 LoggerInterface
237
-     *
238
-     * @param string $message
239
-     * @param int $level
240
-     */
241
-    public function log($message, $level)
242
-    {
243
-        Injector::inst()->get(LoggerInterface::class)->log($level, $message);
244
-    }
245
-
246
-    /**
247
-     * Set the HTTP status code that should be returned when there's an error.
248
-     *
249
-     * @param int $errorCode
250
-     */
251
-    public function setErrorCode($errorCode)
252
-    {
253
-        $this->errorCode = $errorCode;
254
-    }
255
-
256
-    /**
257
-     * @deprecated
258
-     * @param string $from
259
-     */
260
-    public static function set_from_email_address($from)
261
-    {
262
-        Deprecation::notice('2.0', 'Use config API instead');
263
-        Config::modify()->set(__CLASS__, 'from_email_address', $from);
264
-    }
265
-
266
-    /**
267
-     * @deprecated
268
-     * @return null|string
269
-     */
270
-    public static function get_from_email_address()
271
-    {
272
-        Deprecation::notice('2.0', 'Use config API instead');
273
-        return Config::inst()->get(__CLASS__, 'from_email_address');
274
-    }
275
-
276
-    /**
277
-     * @deprecated
278
-     * @param string $to
279
-     */
280
-    public static function set_to_email_address($to)
281
-    {
282
-        Deprecation::notice('2.0', 'Use config API instead');
283
-        Config::modify()->set(__CLASS__, 'to_email_address',  $to);
284
-    }
285
-
286
-    /**
287
-     * @deprecated
288
-     * @return null|string
289
-     */
290
-    public static function get_to_email_address()
291
-    {
292
-        Deprecation::notice('2.0', 'Use config API instead');
293
-        return Config::inst()->get(__CLASS__, 'to_email_address');
294
-    }
295
-
296
-    /**
297
-     * @deprecated
298
-     * @param bool $results
299
-     */
300
-    public static function set_email_results($results)
301
-    {
302
-        Deprecation::notice('2.0', 'Use config API instead');
303
-        Config::modify()->set(__CLASS__, 'email_results', $results);
304
-    }
305
-
306
-    /**
307
-     * @deprecated
308
-     * @return bool
309
-     */
310
-    public static function get_email_results()
311
-    {
312
-        Deprecation::notice('2.0', 'Use config API instead');
313
-        return Config::inst()->get(__CLASS__, 'email_results');
314
-    }
28
+	/**
29
+	 * @var array
30
+	 */
31
+	private static $url_handlers = [
32
+		'' => 'index',
33
+	];
34
+
35
+	/**
36
+	 * @var string
37
+	 */
38
+	protected $checkSuiteName;
39
+
40
+	/**
41
+	 * @var string
42
+	 */
43
+	protected $title;
44
+
45
+	/**
46
+	 * @var int
47
+	 */
48
+	protected $errorCode = 500;
49
+
50
+	/**
51
+	 * @var null|string
52
+	 */
53
+	private static $to_email_address = null;
54
+
55
+	/**
56
+	 * @var null|string
57
+	 */
58
+	private static $from_email_address = null;
59
+
60
+	/**
61
+	 * @var bool
62
+	 */
63
+	private static $email_results = false;
64
+
65
+	/**
66
+	 * @var bool Log results via {@link \Psr\Log\LoggerInterface}
67
+	 */
68
+	private static $log_results_warning = false;
69
+
70
+	/**
71
+	 * @var string Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::WARNING
72
+	 */
73
+	private static $log_results_warning_level = LogLevel::WARNING;
74
+
75
+	/**
76
+	 * @var bool Log results via a {@link \Psr\Log\LoggerInterface}
77
+	 */
78
+	private static $log_results_error = false;
79
+
80
+	/**
81
+	 * @var int Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::ALERT
82
+	 */
83
+	private static $log_results_error_level = LogLevel::ALERT;
84
+
85
+	/**
86
+	 * @param string $checkSuiteName
87
+	 * @param string $title
88
+	 */
89
+	public function __construct($checkSuiteName, $title)
90
+	{
91
+		parent::__construct();
92
+
93
+		$this->checkSuiteName = $checkSuiteName;
94
+		$this->title = $title;
95
+	}
96
+
97
+	/**
98
+	 * @param string $permission
99
+	 *
100
+	 * @throws HTTPResponse_Exception
101
+	 */
102
+	public function init($permission = 'ADMIN')
103
+	{
104
+		// if the environment supports it, provide a basic auth challenge and see if it matches configured credentials
105
+		if (getenv('ENVCHECK_BASICAUTH_USERNAME') && getenv('ENVCHECK_BASICAUTH_PASSWORD')) {
106
+			if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
107
+				// authenticate the input user/pass with the configured credentials
108
+				if (!(
109
+						$_SERVER['PHP_AUTH_USER'] == getenv('ENVCHECK_BASICAUTH_USERNAME')
110
+						&& $_SERVER['PHP_AUTH_PW'] == getenv('ENVCHECK_BASICAUTH_PASSWORD')
111
+					)
112
+				) {
113
+					$response = new HTTPResponse(null, 401);
114
+					$response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
115
+					// Exception is caught by RequestHandler->handleRequest() and will halt further execution
116
+					$e = new HTTPResponse_Exception(null, 401);
117
+					$e->setResponse($response);
118
+					throw $e;
119
+				}
120
+			} else {
121
+				$response = new HTTPResponse(null, 401);
122
+				$response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
123
+				// Exception is caught by RequestHandler->handleRequest() and will halt further execution
124
+				$e = new HTTPResponse_Exception(null, 401);
125
+				$e->setResponse($response);
126
+				throw $e;
127
+			}
128
+		} else {
129
+			if (!$this->canAccess(null, $permission)) {
130
+				return $this->httpError(403);
131
+			}
132
+		}
133
+	}
134
+
135
+	/**
136
+	 * @param null|int|Member $member
137
+	 * @param string $permission
138
+	 *
139
+	 * @return bool
140
+	 *
141
+	 * @throws HTTPResponse_Exception
142
+	 */
143
+	public function canAccess($member = null, $permission = 'ADMIN')
144
+	{
145
+		if (!$member) {
146
+			$member = Member::currentUser();
147
+		}
148
+
149
+		if (!$member) {
150
+			$member = BasicAuth::requireLogin('Environment Checker', $permission, false);
151
+		}
152
+
153
+		// We allow access to this controller regardless of live-status or ADMIN permission only
154
+		// if on CLI.  Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
155
+		if (Director::isDev()
156
+			|| Director::is_cli()
157
+			|| empty($permission)
158
+			|| Permission::checkMember($member, $permission)
159
+		) {
160
+			return true;
161
+		}
162
+
163
+		// Extended access checks.
164
+		// "Veto" style, return NULL to abstain vote.
165
+		$canExtended = null;
166
+		$results = $this->extend('canAccess', $member);
167
+		if ($results && is_array($results)) {
168
+			if (!min($results)) {
169
+				return false;
170
+			}
171
+			return true;
172
+		}
173
+
174
+		return false;
175
+	}
176
+
177
+	/**
178
+	 * @return HTTPResponse
179
+	 */
180
+	public function index()
181
+	{
182
+		$response = new HTTPResponse;
183
+		$result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run();
184
+
185
+		if (!$result->ShouldPass()) {
186
+			$response->setStatusCode($this->errorCode);
187
+		}
188
+
189
+		$resultText = $result->customise([
190
+			'URL' => Director::absoluteBaseURL(),
191
+			'Title' => $this->title,
192
+			'Name' => $this->checkSuiteName,
193
+			'ErrorCode' => $this->errorCode,
194
+		])->renderWith(__CLASS__);
195
+
196
+		if ($this->config()->email_results && !$result->ShouldPass()) {
197
+			$email = new Email(
198
+				$this->config()->from_email_address,
199
+				$this->config()->to_email_address,
200
+				$this->title,
201
+				$resultText
202
+			);
203
+			$email->send();
204
+		}
205
+
206
+		// Optionally log errors and warnings individually
207
+		foreach ($result->Details() as $detail) {
208
+			if ($this->config()->log_results_warning && $detail->StatusCode == EnvironmentCheck::WARNING) {
209
+				$this->log(
210
+					sprintf('EnvironmentChecker warning at "%s" check. Message: %s', $detail->Check, $detail->Message),
211
+					$this->config()->log_results_warning_level
212
+				);
213
+			} elseif ($this->config()->log_results_error && $detail->StatusCode == EnvironmentCheck::ERROR) {
214
+				$this->log(
215
+					sprintf('EnvironmentChecker error at "%s" check. Message: %s', $detail->Check, $detail->Message),
216
+					$this->config()->log_results_error_level
217
+				);
218
+			}
219
+		}
220
+
221
+		// output the result as JSON if requested
222
+		if ($this->getRequest()->getExtension() == 'json'
223
+			|| strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false
224
+		) {
225
+			$response->setBody($result->toJSON());
226
+			$response->addHeader('Content-Type', 'application/json');
227
+			return $response;
228
+		}
229
+
230
+		$response->setBody($resultText);
231
+
232
+		return $response;
233
+	}
234
+
235
+	/**
236
+	 * Sends a log entry to the configured PSR-3 LoggerInterface
237
+	 *
238
+	 * @param string $message
239
+	 * @param int $level
240
+	 */
241
+	public function log($message, $level)
242
+	{
243
+		Injector::inst()->get(LoggerInterface::class)->log($level, $message);
244
+	}
245
+
246
+	/**
247
+	 * Set the HTTP status code that should be returned when there's an error.
248
+	 *
249
+	 * @param int $errorCode
250
+	 */
251
+	public function setErrorCode($errorCode)
252
+	{
253
+		$this->errorCode = $errorCode;
254
+	}
255
+
256
+	/**
257
+	 * @deprecated
258
+	 * @param string $from
259
+	 */
260
+	public static function set_from_email_address($from)
261
+	{
262
+		Deprecation::notice('2.0', 'Use config API instead');
263
+		Config::modify()->set(__CLASS__, 'from_email_address', $from);
264
+	}
265
+
266
+	/**
267
+	 * @deprecated
268
+	 * @return null|string
269
+	 */
270
+	public static function get_from_email_address()
271
+	{
272
+		Deprecation::notice('2.0', 'Use config API instead');
273
+		return Config::inst()->get(__CLASS__, 'from_email_address');
274
+	}
275
+
276
+	/**
277
+	 * @deprecated
278
+	 * @param string $to
279
+	 */
280
+	public static function set_to_email_address($to)
281
+	{
282
+		Deprecation::notice('2.0', 'Use config API instead');
283
+		Config::modify()->set(__CLASS__, 'to_email_address',  $to);
284
+	}
285
+
286
+	/**
287
+	 * @deprecated
288
+	 * @return null|string
289
+	 */
290
+	public static function get_to_email_address()
291
+	{
292
+		Deprecation::notice('2.0', 'Use config API instead');
293
+		return Config::inst()->get(__CLASS__, 'to_email_address');
294
+	}
295
+
296
+	/**
297
+	 * @deprecated
298
+	 * @param bool $results
299
+	 */
300
+	public static function set_email_results($results)
301
+	{
302
+		Deprecation::notice('2.0', 'Use config API instead');
303
+		Config::modify()->set(__CLASS__, 'email_results', $results);
304
+	}
305
+
306
+	/**
307
+	 * @deprecated
308
+	 * @return bool
309
+	 */
310
+	public static function get_email_results()
311
+	{
312
+		Deprecation::notice('2.0', 'Use config API instead');
313
+		return Config::inst()->get(__CLASS__, 'email_results');
314
+	}
315 315
 }
Please login to merge, or discard this patch.
src/EnvironmentCheckSuiteResult.php 1 patch
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -14,112 +14,112 @@
 block discarded – undo
14 14
  */
15 15
 class EnvironmentCheckSuiteResult extends ViewableData
16 16
 {
17
-    /**
18
-     * @var ArrayList
19
-     */
20
-    protected $details;
17
+	/**
18
+	 * @var ArrayList
19
+	 */
20
+	protected $details;
21 21
 
22
-    /**
23
-     * @var int
24
-     */
25
-    protected $worst = 0;
22
+	/**
23
+	 * @var int
24
+	 */
25
+	protected $worst = 0;
26 26
 
27
-    public function __construct()
28
-    {
29
-        parent::__construct();
30
-        $this->details = new ArrayList();
31
-    }
27
+	public function __construct()
28
+	{
29
+		parent::__construct();
30
+		$this->details = new ArrayList();
31
+	}
32 32
 
33
-    /**
34
-     * @param int $status
35
-     * @param string $message
36
-     * @param string $checkIdentifier
37
-     */
38
-    public function addResult($status, $message, $checkIdentifier)
39
-    {
40
-        $this->details->push(new ArrayData([
41
-            'Check' => $checkIdentifier,
42
-            'Status' => $this->statusText($status),
43
-            'StatusCode' => $status,
44
-            'Message' => $message,
45
-        ]));
33
+	/**
34
+	 * @param int $status
35
+	 * @param string $message
36
+	 * @param string $checkIdentifier
37
+	 */
38
+	public function addResult($status, $message, $checkIdentifier)
39
+	{
40
+		$this->details->push(new ArrayData([
41
+			'Check' => $checkIdentifier,
42
+			'Status' => $this->statusText($status),
43
+			'StatusCode' => $status,
44
+			'Message' => $message,
45
+		]));
46 46
 
47
-        $this->worst = max($this->worst, $status);
48
-    }
47
+		$this->worst = max($this->worst, $status);
48
+	}
49 49
 
50
-    /**
51
-     * Returns true if there are no errors.
52
-     *
53
-     * @return bool
54
-     */
55
-    public function ShouldPass()
56
-    {
57
-        return $this->worst <= EnvironmentCheck::WARNING;
58
-    }
50
+	/**
51
+	 * Returns true if there are no errors.
52
+	 *
53
+	 * @return bool
54
+	 */
55
+	public function ShouldPass()
56
+	{
57
+		return $this->worst <= EnvironmentCheck::WARNING;
58
+	}
59 59
 
60
-    /**
61
-     * Returns overall (i.e. worst) status as a string.
62
-     *
63
-     * @return string
64
-     */
65
-    public function Status()
66
-    {
67
-        return $this->statusText($this->worst);
68
-    }
60
+	/**
61
+	 * Returns overall (i.e. worst) status as a string.
62
+	 *
63
+	 * @return string
64
+	 */
65
+	public function Status()
66
+	{
67
+		return $this->statusText($this->worst);
68
+	}
69 69
 
70
-    /**
71
-     * Returns detailed status information about each check.
72
-     *
73
-     * @return ArrayList
74
-     */
75
-    public function Details()
76
-    {
77
-        return $this->details;
78
-    }
70
+	/**
71
+	 * Returns detailed status information about each check.
72
+	 *
73
+	 * @return ArrayList
74
+	 */
75
+	public function Details()
76
+	{
77
+		return $this->details;
78
+	}
79 79
 
80
-    /**
81
-     * Convert the final result status and details to JSON.
82
-     *
83
-     * @return string
84
-     */
85
-    public function toJSON()
86
-    {
87
-        $result = [
88
-            'Status' => $this->Status(),
89
-            'ShouldPass' => $this->ShouldPass(),
90
-            'Checks' => []
91
-        ];
92
-        foreach ($this->details as $detail) {
93
-            $result['Checks'][] = $detail->toMap();
94
-        }
95
-        return json_encode($result);
96
-    }
80
+	/**
81
+	 * Convert the final result status and details to JSON.
82
+	 *
83
+	 * @return string
84
+	 */
85
+	public function toJSON()
86
+	{
87
+		$result = [
88
+			'Status' => $this->Status(),
89
+			'ShouldPass' => $this->ShouldPass(),
90
+			'Checks' => []
91
+		];
92
+		foreach ($this->details as $detail) {
93
+			$result['Checks'][] = $detail->toMap();
94
+		}
95
+		return json_encode($result);
96
+	}
97 97
 
98
-    /**
99
-     * Return a text version of a status code.
100
-     *
101
-     * @param  int $status
102
-     * @return string
103
-     * @throws InvalidArgumentException
104
-     */
105
-    protected function statusText($status)
106
-    {
107
-        switch ($status) {
108
-            case EnvironmentCheck::ERROR:
109
-                return 'ERROR';
110
-                break;
111
-            case EnvironmentCheck::WARNING:
112
-                return 'WARNING';
113
-                break;
114
-            case EnvironmentCheck::OK:
115
-                return 'OK';
116
-                break;
117
-            case 0:
118
-                return 'NO CHECKS';
119
-                break;
120
-            default:
121
-                throw new InvalidArgumentException("Bad environment check status '$status'");
122
-                break;
123
-        }
124
-    }
98
+	/**
99
+	 * Return a text version of a status code.
100
+	 *
101
+	 * @param  int $status
102
+	 * @return string
103
+	 * @throws InvalidArgumentException
104
+	 */
105
+	protected function statusText($status)
106
+	{
107
+		switch ($status) {
108
+			case EnvironmentCheck::ERROR:
109
+				return 'ERROR';
110
+				break;
111
+			case EnvironmentCheck::WARNING:
112
+				return 'WARNING';
113
+				break;
114
+			case EnvironmentCheck::OK:
115
+				return 'OK';
116
+				break;
117
+			case 0:
118
+				return 'NO CHECKS';
119
+				break;
120
+			default:
121
+				throw new InvalidArgumentException("Bad environment check status '$status'");
122
+				break;
123
+		}
124
+	}
125 125
 }
Please login to merge, or discard this patch.
src/Checks/SolrIndexCheck.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -13,53 +13,53 @@
 block discarded – undo
13 13
  */
14 14
 class SolrIndexCheck implements EnvironmentCheck
15 15
 {
16
-    /**
17
-     * @var null|string
18
-     */
19
-    protected $indexClass;
16
+	/**
17
+	 * @var null|string
18
+	 */
19
+	protected $indexClass;
20 20
 
21
-    /**
22
-     * @param string $indexClass Limit the index checks to the specified class and all its subclasses.
23
-     */
24
-    public function __construct($indexClass = null)
25
-    {
26
-        $this->indexClass = $indexClass;
27
-    }
21
+	/**
22
+	 * @param string $indexClass Limit the index checks to the specified class and all its subclasses.
23
+	 */
24
+	public function __construct($indexClass = null)
25
+	{
26
+		$this->indexClass = $indexClass;
27
+	}
28 28
 
29
-    /**
30
-     * {@inheritDoc}
31
-     *
32
-     * @return array
33
-     */
34
-    public function check()
35
-    {
36
-        $brokenCores = [];
29
+	/**
30
+	 * {@inheritDoc}
31
+	 *
32
+	 * @return array
33
+	 */
34
+	public function check()
35
+	{
36
+		$brokenCores = [];
37 37
 
38
-        /**
39
-         * @todo Revisit this when silverstripe/fulltextsearch has 4.x compat
40
-         */
41
-        if (!class_exists('\\Solr')) {
42
-            return [
43
-                EnvironmentCheck::ERROR,
44
-                'Class `Solr` not found. Is the fulltextsearch module installed?'
45
-            ];
46
-        }
38
+		/**
39
+		 * @todo Revisit this when silverstripe/fulltextsearch has 4.x compat
40
+		 */
41
+		if (!class_exists('\\Solr')) {
42
+			return [
43
+				EnvironmentCheck::ERROR,
44
+				'Class `Solr` not found. Is the fulltextsearch module installed?'
45
+			];
46
+		}
47 47
 
48
-        $service = \Solr::service();
49
-        foreach (\Solr::get_indexes($this->indexClass) as $index) {
50
-            $core = $index->getIndexName();
51
-            if (!$service->coreIsActive($core)) {
52
-                $brokenCores[] = $core;
53
-            }
54
-        }
48
+		$service = \Solr::service();
49
+		foreach (\Solr::get_indexes($this->indexClass) as $index) {
50
+			$core = $index->getIndexName();
51
+			if (!$service->coreIsActive($core)) {
52
+				$brokenCores[] = $core;
53
+			}
54
+		}
55 55
 
56
-        if (!empty($brokenCores)) {
57
-            return [
58
-                EnvironmentCheck::ERROR,
59
-                'The following indexes are unavailable: ' . implode($brokenCores, ', ')
60
-            ];
61
-        }
56
+		if (!empty($brokenCores)) {
57
+			return [
58
+				EnvironmentCheck::ERROR,
59
+				'The following indexes are unavailable: ' . implode($brokenCores, ', ')
60
+			];
61
+		}
62 62
 
63
-        return [EnvironmentCheck::OK, 'Expected indexes are available.'];
64
-    }
63
+		return [EnvironmentCheck::OK, 'Expected indexes are available.'];
64
+	}
65 65
 }
Please login to merge, or discard this patch.
src/Checks/SMTPConnectCheck.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -13,67 +13,67 @@
 block discarded – undo
13 13
  */
14 14
 class SMTPConnectCheck implements EnvironmentCheck
15 15
 {
16
-    /**
17
-     * @var string
18
-     */
19
-    protected $host;
16
+	/**
17
+	 * @var string
18
+	 */
19
+	protected $host;
20 20
 
21
-    /**
22
-     * @var int
23
-     */
24
-    protected $port;
21
+	/**
22
+	 * @var int
23
+	 */
24
+	protected $port;
25 25
 
26
-    /**
27
-     * Timeout (in seconds).
28
-     *
29
-     * @var int
30
-     */
31
-    protected $timeout;
26
+	/**
27
+	 * Timeout (in seconds).
28
+	 *
29
+	 * @var int
30
+	 */
31
+	protected $timeout;
32 32
 
33
-    /**
34
-     * @param null|string $host
35
-     * @param null|int $port
36
-     * @param int $timeout
37
-     */
38
-    public function __construct($host = null, $port = null, $timeout = 15)
39
-    {
40
-        $this->host = ($host) ? $host : ini_get('SMTP');
41
-        if (!$this->host) {
42
-            $this->host = 'localhost';
43
-        }
33
+	/**
34
+	 * @param null|string $host
35
+	 * @param null|int $port
36
+	 * @param int $timeout
37
+	 */
38
+	public function __construct($host = null, $port = null, $timeout = 15)
39
+	{
40
+		$this->host = ($host) ? $host : ini_get('SMTP');
41
+		if (!$this->host) {
42
+			$this->host = 'localhost';
43
+		}
44 44
 
45
-        $this->port = ($port) ? $port : ini_get('smtp_port');
46
-        if (!$this->port) {
47
-            $this->port = 25;
48
-        }
45
+		$this->port = ($port) ? $port : ini_get('smtp_port');
46
+		if (!$this->port) {
47
+			$this->port = 25;
48
+		}
49 49
 
50
-        $this->timeout = $timeout;
51
-    }
50
+		$this->timeout = $timeout;
51
+	}
52 52
 
53
-    /**
54
-     * {@inheritDoc}
55
-     *
56
-     * @return array
57
-     */
58
-    public function check()
59
-    {
60
-        $f = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
61
-        if (!$f) {
62
-            return [
63
-                EnvironmentCheck::ERROR,
64
-                sprintf("Couldn't connect to SMTP on %s:%s (Error: %s %s)", $this->host, $this->port, $errno, $errstr)
65
-            ];
66
-        }
53
+	/**
54
+	 * {@inheritDoc}
55
+	 *
56
+	 * @return array
57
+	 */
58
+	public function check()
59
+	{
60
+		$f = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
61
+		if (!$f) {
62
+			return [
63
+				EnvironmentCheck::ERROR,
64
+				sprintf("Couldn't connect to SMTP on %s:%s (Error: %s %s)", $this->host, $this->port, $errno, $errstr)
65
+			];
66
+		}
67 67
 
68
-        fwrite($f, "HELO its_me\r\n");
69
-        $response = fread($f, 26);
70
-        if (substr($response, 0, 3) != '220') {
71
-            return [
72
-                EnvironmentCheck::ERROR,
73
-                sprintf('Invalid mail server response: %s', $response)
74
-            ];
75
-        }
68
+		fwrite($f, "HELO its_me\r\n");
69
+		$response = fread($f, 26);
70
+		if (substr($response, 0, 3) != '220') {
71
+			return [
72
+				EnvironmentCheck::ERROR,
73
+				sprintf('Invalid mail server response: %s', $response)
74
+			];
75
+		}
76 76
 
77
-        return [EnvironmentCheck::OK, ''];
78
-    }
77
+		return [EnvironmentCheck::OK, ''];
78
+	}
79 79
 }
Please login to merge, or discard this patch.
src/Checks/DatabaseCheck.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -13,38 +13,38 @@
 block discarded – undo
13 13
  */
14 14
 class DatabaseCheck implements EnvironmentCheck
15 15
 {
16
-    /**
17
-     * @var string
18
-     */
19
-    protected $checkTable;
20
-
21
-    /**
22
-     * By default, Member will be checked.
23
-     *
24
-     * @param string $checkTable
25
-     */
26
-    public function __construct($checkTable = 'Member')
27
-    {
28
-        $this->checkTable = $checkTable;
29
-    }
30
-
31
-    /**
32
-     * {@inheritDoc}
33
-     *
34
-     * @return array
35
-     */
36
-    public function check()
37
-    {
38
-        if (!DB::get_schema()->hasTable($this->checkTable)) {
39
-            return [EnvironmentCheck::ERROR, "$this->checkTable not present in the database"];
40
-        }
41
-
42
-        $count = DB::query("SELECT COUNT(*) FROM \"$this->checkTable\"")->value();
43
-
44
-        if ($count > 0) {
45
-            return [EnvironmentCheck::OK, ''];
46
-        }
47
-
48
-        return [EnvironmentCheck::WARNING, "$this->checkTable queried ok but has no records"];
49
-    }
16
+	/**
17
+	 * @var string
18
+	 */
19
+	protected $checkTable;
20
+
21
+	/**
22
+	 * By default, Member will be checked.
23
+	 *
24
+	 * @param string $checkTable
25
+	 */
26
+	public function __construct($checkTable = 'Member')
27
+	{
28
+		$this->checkTable = $checkTable;
29
+	}
30
+
31
+	/**
32
+	 * {@inheritDoc}
33
+	 *
34
+	 * @return array
35
+	 */
36
+	public function check()
37
+	{
38
+		if (!DB::get_schema()->hasTable($this->checkTable)) {
39
+			return [EnvironmentCheck::ERROR, "$this->checkTable not present in the database"];
40
+		}
41
+
42
+		$count = DB::query("SELECT COUNT(*) FROM \"$this->checkTable\"")->value();
43
+
44
+		if ($count > 0) {
45
+			return [EnvironmentCheck::OK, ''];
46
+		}
47
+
48
+		return [EnvironmentCheck::WARNING, "$this->checkTable queried ok but has no records"];
49
+	}
50 50
 }
Please login to merge, or discard this patch.
src/Checks/HasFunctionCheck.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -11,29 +11,29 @@
 block discarded – undo
11 11
  */
12 12
 class HasFunctionCheck implements EnvironmentCheck
13 13
 {
14
-    /**
15
-     * @var string
16
-     */
17
-    protected $functionName;
14
+	/**
15
+	 * @var string
16
+	 */
17
+	protected $functionName;
18 18
 
19
-    /**
20
-     * @param string $functionName The name of the function to look for.
21
-     */
22
-    public function __construct($functionName)
23
-    {
24
-        $this->functionName = $functionName;
25
-    }
19
+	/**
20
+	 * @param string $functionName The name of the function to look for.
21
+	 */
22
+	public function __construct($functionName)
23
+	{
24
+		$this->functionName = $functionName;
25
+	}
26 26
 
27
-    /**
28
-     * {@inheritDoc}
29
-     *
30
-     * @return array
31
-     */
32
-    public function check()
33
-    {
34
-        if (function_exists($this->functionName)) {
35
-            return [EnvironmentCheck::OK, $this->functionName . '() exists'];
36
-        }
37
-        return [EnvironmentCheck::ERROR, $this->functionName . '() doesn\'t exist'];
38
-    }
27
+	/**
28
+	 * {@inheritDoc}
29
+	 *
30
+	 * @return array
31
+	 */
32
+	public function check()
33
+	{
34
+		if (function_exists($this->functionName)) {
35
+			return [EnvironmentCheck::OK, $this->functionName . '() exists'];
36
+		}
37
+		return [EnvironmentCheck::ERROR, $this->functionName . '() doesn\'t exist'];
38
+	}
39 39
 }
Please login to merge, or discard this patch.