Completed
Push — master ( f74c37...128ddb )
by Robbie
21s queued 10s
created
tests/Checks/DatabaseCheckTest.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -16,25 +16,25 @@
 block discarded – undo
16 16
  */
17 17
 class DatabaseCheckTest extends SapphireTest
18 18
 {
19
-    /**
20
-     * {@inheritDoc}
21
-     * @var bool
22
-     */
23
-    protected $usesDatabase = true;
19
+	/**
20
+	 * {@inheritDoc}
21
+	 * @var bool
22
+	 */
23
+	protected $usesDatabase = true;
24 24
 
25
-    public function testCheckReportsValidConnection()
26
-    {
27
-        $member = new Member;
28
-        $member->FirstName = 'Bob';
29
-        $member->write();
25
+	public function testCheckReportsValidConnection()
26
+	{
27
+		$member = new Member;
28
+		$member->FirstName = 'Bob';
29
+		$member->write();
30 30
 
31
-        $check = new DatabaseCheck();
31
+		$check = new DatabaseCheck();
32 32
 
33
-        $expected = [
34
-            EnvironmentCheck::OK,
35
-            ''
36
-        ];
33
+		$expected = [
34
+			EnvironmentCheck::OK,
35
+			''
36
+		];
37 37
 
38
-        $this->assertEquals($expected, $check->check());
39
-    }
38
+		$this->assertEquals($expected, $check->check());
39
+	}
40 40
 }
Please login to merge, or discard this patch.
tests/Checks/HasFunctionCheckTest.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -15,27 +15,27 @@
 block discarded – undo
15 15
  */
16 16
 class HasFunctionCheckTest extends SapphireTest
17 17
 {
18
-    public function testCheckReportsMissingFunctions()
19
-    {
20
-        $check = new HasFunctionCheck('foo');
18
+	public function testCheckReportsMissingFunctions()
19
+	{
20
+		$check = new HasFunctionCheck('foo');
21 21
 
22
-        $expected = [
23
-            EnvironmentCheck::ERROR,
24
-            'foo() doesn\'t exist'
25
-        ];
22
+		$expected = [
23
+			EnvironmentCheck::ERROR,
24
+			'foo() doesn\'t exist'
25
+		];
26 26
 
27
-        $this->assertEquals($expected, $check->check());
28
-    }
27
+		$this->assertEquals($expected, $check->check());
28
+	}
29 29
 
30
-    public function testCheckReportsFoundFunctions()
31
-    {
32
-        $check = new HasFunctionCheck('class_exists');
30
+	public function testCheckReportsFoundFunctions()
31
+	{
32
+		$check = new HasFunctionCheck('class_exists');
33 33
 
34
-        $expected = [
35
-            EnvironmentCheck::OK,
36
-            'class_exists() exists'
37
-        ];
34
+		$expected = [
35
+			EnvironmentCheck::OK,
36
+			'class_exists() exists'
37
+		];
38 38
 
39
-        $this->assertEquals($expected, $check->check());
40
-    }
39
+		$this->assertEquals($expected, $check->check());
40
+	}
41 41
 }
Please login to merge, or discard this patch.
tests/EnvironmentCheckerTest.php 1 patch
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -18,80 +18,80 @@
 block discarded – undo
18 18
  */
19 19
 class EnvironmentCheckerTest extends SapphireTest
20 20
 {
21
-    protected $usesDatabase = true;
21
+	protected $usesDatabase = true;
22 22
 
23
-    protected function tearDown()
24
-    {
25
-        EnvironmentCheckSuite::reset();
26
-        parent::tearDown();
27
-    }
23
+	protected function tearDown()
24
+	{
25
+		EnvironmentCheckSuite::reset();
26
+		parent::tearDown();
27
+	}
28 28
 
29
-    public function testOnlyLogsWithErrors()
30
-    {
31
-        Config::modify()->set(EnvironmentChecker::class, 'log_results_warning', true);
32
-        Config::modify()->set(EnvironmentChecker::class, 'log_results_error', true);
29
+	public function testOnlyLogsWithErrors()
30
+	{
31
+		Config::modify()->set(EnvironmentChecker::class, 'log_results_warning', true);
32
+		Config::modify()->set(EnvironmentChecker::class, 'log_results_error', true);
33 33
 
34
-        EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest\CheckNoErrors());
34
+		EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest\CheckNoErrors());
35 35
 
36
-        $logger = $this->getMockBuilder(Logger::class)
37
-            ->disableOriginalConstructor()
38
-            ->setMethods(['log'])
39
-            ->getMock();
36
+		$logger = $this->getMockBuilder(Logger::class)
37
+			->disableOriginalConstructor()
38
+			->setMethods(['log'])
39
+			->getMock();
40 40
 
41
-        $logger->expects($this->never())->method('log');
41
+		$logger->expects($this->never())->method('log');
42 42
 
43
-        Injector::inst()->registerService($logger, LoggerInterface::class);
43
+		Injector::inst()->registerService($logger, LoggerInterface::class);
44 44
 
45
-        (new EnvironmentChecker('test suite', 'test'))->index();
46
-    }
45
+		(new EnvironmentChecker('test suite', 'test'))->index();
46
+	}
47 47
 
48
-    public function testLogsWithWarnings()
49
-    {
50
-        Config::modify()->set(EnvironmentChecker::class, 'log_results_warning', true);
51
-        Config::modify()->set(EnvironmentChecker::class, 'log_results_error', false);
48
+	public function testLogsWithWarnings()
49
+	{
50
+		Config::modify()->set(EnvironmentChecker::class, 'log_results_warning', true);
51
+		Config::modify()->set(EnvironmentChecker::class, 'log_results_error', false);
52 52
 
53
-        EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest\CheckWarnings());
54
-        EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest\CheckErrors());
53
+		EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest\CheckWarnings());
54
+		EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest\CheckErrors());
55 55
 
56
-        $logger = $this->getMockBuilder(Logger::class)
57
-            ->disableOriginalConstructor()
58
-            ->setMethods(['log'])
59
-            ->getMock();
56
+		$logger = $this->getMockBuilder(Logger::class)
57
+			->disableOriginalConstructor()
58
+			->setMethods(['log'])
59
+			->getMock();
60 60
 
61
-        $logger->expects($this->once())
62
-            ->method('log')
63
-            ->withConsecutive(
64
-                $this->equalTo(LogLevel::WARNING),
65
-                $this->anything()
66
-            );
61
+		$logger->expects($this->once())
62
+			->method('log')
63
+			->withConsecutive(
64
+				$this->equalTo(LogLevel::WARNING),
65
+				$this->anything()
66
+			);
67 67
 
68
-        Injector::inst()->registerService($logger, LoggerInterface::class);
68
+		Injector::inst()->registerService($logger, LoggerInterface::class);
69 69
 
70
-        (new EnvironmentChecker('test suite', 'test'))->index();
71
-    }
70
+		(new EnvironmentChecker('test suite', 'test'))->index();
71
+	}
72 72
 
73
-    public function testLogsWithErrors()
74
-    {
75
-        Config::modify()->set(EnvironmentChecker::class, 'log_results_error', false);
76
-        Config::modify()->set(EnvironmentChecker::class, 'log_results_error', true);
73
+	public function testLogsWithErrors()
74
+	{
75
+		Config::modify()->set(EnvironmentChecker::class, 'log_results_error', false);
76
+		Config::modify()->set(EnvironmentChecker::class, 'log_results_error', true);
77 77
 
78
-        EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest\CheckWarnings());
79
-        EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest\CheckErrors());
78
+		EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest\CheckWarnings());
79
+		EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest\CheckErrors());
80 80
 
81
-        $logger = $this->getMockBuilder(Logger::class)
82
-            ->disableOriginalConstructor()
83
-            ->setMethods(['log'])
84
-            ->getMock();
81
+		$logger = $this->getMockBuilder(Logger::class)
82
+			->disableOriginalConstructor()
83
+			->setMethods(['log'])
84
+			->getMock();
85 85
 
86
-        $logger->expects($this->once())
87
-            ->method('log')
88
-            ->withConsecutive(
89
-                [$this->equalTo(LogLevel::ALERT), $this->anything()],
90
-                [$this->equalTo(LogLevel::WARNING), $this->anything()]
91
-            );
86
+		$logger->expects($this->once())
87
+			->method('log')
88
+			->withConsecutive(
89
+				[$this->equalTo(LogLevel::ALERT), $this->anything()],
90
+				[$this->equalTo(LogLevel::WARNING), $this->anything()]
91
+			);
92 92
 
93
-        Injector::inst()->registerService($logger, LoggerInterface::class);
93
+		Injector::inst()->registerService($logger, LoggerInterface::class);
94 94
 
95
-        (new EnvironmentChecker('test suite', 'test'))->index();
96
-    }
95
+		(new EnvironmentChecker('test suite', 'test'))->index();
96
+	}
97 97
 }
Please login to merge, or discard this patch.
tests/EnvironmentCheckerTest/CheckNoErrors.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -7,8 +7,8 @@
 block discarded – undo
7 7
 
8 8
 class CheckNoErrors implements EnvironmentCheck, TestOnly
9 9
 {
10
-    public function check()
11
-    {
12
-        return [EnvironmentCheck::OK, ''];
13
-    }
10
+	public function check()
11
+	{
12
+		return [EnvironmentCheck::OK, ''];
13
+	}
14 14
 }
Please login to merge, or discard this patch.
tests/EnvironmentCheckerTest/CheckErrors.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -7,8 +7,8 @@
 block discarded – undo
7 7
 
8 8
 class CheckErrors implements EnvironmentCheck, TestOnly
9 9
 {
10
-    public function check()
11
-    {
12
-        return [EnvironmentCheck::ERROR, 'test error'];
13
-    }
10
+	public function check()
11
+	{
12
+		return [EnvironmentCheck::ERROR, 'test error'];
13
+	}
14 14
 }
Please login to merge, or discard this patch.
tests/EnvironmentCheckerTest/CheckWarnings.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -7,8 +7,8 @@
 block discarded – undo
7 7
 
8 8
 class CheckWarnings implements EnvironmentCheck, TestOnly
9 9
 {
10
-    public function check()
11
-    {
12
-        return [EnvironmentCheck::WARNING, 'test warning'];
13
-    }
10
+	public function check()
11
+	{
12
+		return [EnvironmentCheck::WARNING, 'test warning'];
13
+	}
14 14
 }
Please login to merge, or discard this patch.
src/EnvironmentChecker.php 1 patch
Indentation   +289 added lines, -289 removed lines patch added patch discarded remove patch
@@ -24,293 +24,293 @@
 block discarded – undo
24 24
  */
25 25
 class EnvironmentChecker extends RequestHandler
26 26
 {
27
-    /**
28
-     * @var array
29
-     */
30
-    private static $url_handlers = [
31
-        '' => 'index',
32
-    ];
33
-
34
-    /**
35
-     * @var string
36
-     */
37
-    protected $checkSuiteName;
38
-
39
-    /**
40
-     * @var string
41
-     */
42
-    protected $title;
43
-
44
-    /**
45
-     * @var int
46
-     */
47
-    protected $errorCode = 500;
48
-
49
-    /**
50
-     * @var null|string
51
-     */
52
-    private static $to_email_address = null;
53
-
54
-    /**
55
-     * @var null|string
56
-     */
57
-    private static $from_email_address = null;
58
-
59
-    /**
60
-     * @var bool
61
-     */
62
-    private static $email_results = false;
63
-
64
-    /**
65
-     * @var bool Log results via {@link \Psr\Log\LoggerInterface}
66
-     */
67
-    private static $log_results_warning = false;
68
-
69
-    /**
70
-     * @var string Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::WARNING
71
-     */
72
-    private static $log_results_warning_level = LogLevel::WARNING;
73
-
74
-    /**
75
-     * @var bool Log results via a {@link \Psr\Log\LoggerInterface}
76
-     */
77
-    private static $log_results_error = false;
78
-
79
-    /**
80
-     * @var int Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::ALERT
81
-     */
82
-    private static $log_results_error_level = LogLevel::ALERT;
83
-
84
-    /**
85
-     * @param string $checkSuiteName
86
-     * @param string $title
87
-     */
88
-    public function __construct($checkSuiteName, $title)
89
-    {
90
-        parent::__construct();
91
-
92
-        $this->checkSuiteName = $checkSuiteName;
93
-        $this->title = $title;
94
-    }
95
-
96
-    /**
97
-     * @param string $permission
98
-     *
99
-     * @throws HTTPResponse_Exception
100
-     */
101
-    public function init($permission = 'ADMIN')
102
-    {
103
-        // if the environment supports it, provide a basic auth challenge and see if it matches configured credentials
104
-        if (Environment::getEnv('ENVCHECK_BASICAUTH_USERNAME')
105
-            && Environment::getEnv('ENVCHECK_BASICAUTH_PASSWORD')
106
-        ) {
107
-            if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
108
-                // authenticate the input user/pass with the configured credentials
109
-                if (!(
110
-                        $_SERVER['PHP_AUTH_USER'] == Environment::getEnv('ENVCHECK_BASICAUTH_USERNAME')
111
-                        && $_SERVER['PHP_AUTH_PW'] == Environment::getEnv('ENVCHECK_BASICAUTH_PASSWORD')
112
-                    )
113
-                ) {
114
-                    $response = new HTTPResponse(null, 401);
115
-                    $response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
116
-                    // Exception is caught by RequestHandler->handleRequest() and will halt further execution
117
-                    $e = new HTTPResponse_Exception(null, 401);
118
-                    $e->setResponse($response);
119
-                    throw $e;
120
-                }
121
-            } else {
122
-                $response = new HTTPResponse(null, 401);
123
-                $response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
124
-                // Exception is caught by RequestHandler->handleRequest() and will halt further execution
125
-                $e = new HTTPResponse_Exception(null, 401);
126
-                $e->setResponse($response);
127
-                throw $e;
128
-            }
129
-        } else {
130
-            if (!$this->canAccess(null, $permission)) {
131
-                return $this->httpError(403);
132
-            }
133
-        }
134
-    }
135
-
136
-    /**
137
-     * @param null|int|Member $member
138
-     * @param string $permission
139
-     *
140
-     * @return bool
141
-     *
142
-     * @throws HTTPResponse_Exception
143
-     */
144
-    public function canAccess($member = null, $permission = 'ADMIN')
145
-    {
146
-        if (!$member) {
147
-            $member = Security::getCurrentUser();
148
-        }
149
-
150
-        if (!$member) {
151
-            $member = BasicAuth::requireLogin($this->getRequest(), 'Environment Checker', $permission, false);
152
-        }
153
-
154
-        // We allow access to this controller regardless of live-status or ADMIN permission only
155
-        // if on CLI.  Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
156
-        if (Director::isDev()
157
-            || Director::is_cli()
158
-            || empty($permission)
159
-            || Permission::checkMember($member, $permission)
160
-        ) {
161
-            return true;
162
-        }
163
-
164
-        // Extended access checks.
165
-        // "Veto" style, return NULL to abstain vote.
166
-        $canExtended = null;
167
-        $results = $this->extend('canAccess', $member);
168
-        if ($results && is_array($results)) {
169
-            if (!min($results)) {
170
-                return false;
171
-            }
172
-            return true;
173
-        }
174
-
175
-        return false;
176
-    }
177
-
178
-    /**
179
-     * @return HTTPResponse
180
-     */
181
-    public function index()
182
-    {
183
-        $response = new HTTPResponse;
184
-        $result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run();
185
-
186
-        if (!$result->ShouldPass()) {
187
-            $response->setStatusCode($this->errorCode);
188
-        }
189
-
190
-        $resultText = $result->customise([
191
-            'URL' => Director::absoluteBaseURL(),
192
-            'Title' => $this->title,
193
-            'Name' => $this->checkSuiteName,
194
-            'ErrorCode' => $this->errorCode,
195
-        ])->renderWith(__CLASS__);
196
-
197
-        if ($this->config()->get('email_results') && !$result->ShouldPass()) {
198
-            $email = new Email(
199
-                $this->config()->get('from_email_address'),
200
-                $this->config()->get('to_email_address'),
201
-                $this->title,
202
-                $resultText
203
-            );
204
-            $email->send();
205
-        }
206
-
207
-        // Optionally log errors and warnings individually
208
-        foreach ($result->Details() as $detail) {
209
-            if ($this->config()->get('log_results_warning') && $detail->StatusCode == EnvironmentCheck::WARNING) {
210
-                $this->log(
211
-                    sprintf('EnvironmentChecker warning at "%s" check. Message: %s', $detail->Check, $detail->Message),
212
-                    $this->config()->get('log_results_warning_level')
213
-                );
214
-            } elseif ($this->config()->get('log_results_error') && $detail->StatusCode == EnvironmentCheck::ERROR) {
215
-                $this->log(
216
-                    sprintf('EnvironmentChecker error at "%s" check. Message: %s', $detail->Check, $detail->Message),
217
-                    $this->config()->get('log_results_error_level')
218
-                );
219
-            }
220
-        }
221
-
222
-        // output the result as JSON if requested
223
-        if ($this->getRequest()->getExtension() == 'json'
224
-            || strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false
225
-        ) {
226
-            $response->setBody($result->toJSON());
227
-            $response->addHeader('Content-Type', 'application/json');
228
-            return $response;
229
-        }
230
-
231
-        $response->setBody($resultText);
232
-
233
-        return $response;
234
-    }
235
-
236
-    /**
237
-     * Sends a log entry to the configured PSR-3 LoggerInterface
238
-     *
239
-     * @param string $message
240
-     * @param int $level
241
-     */
242
-    public function log($message, $level)
243
-    {
244
-        Injector::inst()->get(LoggerInterface::class)->log($level, $message);
245
-    }
246
-
247
-    /**
248
-     * Set the HTTP status code that should be returned when there's an error.
249
-     *
250
-     * @param int $errorCode
251
-     */
252
-    public function setErrorCode($errorCode)
253
-    {
254
-        $this->errorCode = $errorCode;
255
-    }
256
-
257
-    /**
258
-     * @deprecated
259
-     * @param string $from
260
-     */
261
-    public static function set_from_email_address($from)
262
-    {
263
-        Deprecation::notice('2.0', 'Use config API instead');
264
-        static::config()->set('from_email_address', $from);
265
-    }
266
-
267
-    /**
268
-     * @deprecated
269
-     * @return null|string
270
-     */
271
-    public static function get_from_email_address()
272
-    {
273
-        Deprecation::notice('2.0', 'Use config API instead');
274
-        return static::config()->get('from_email_address');
275
-    }
276
-
277
-    /**
278
-     * @deprecated
279
-     * @param string $to
280
-     */
281
-    public static function set_to_email_address($to)
282
-    {
283
-        Deprecation::notice('2.0', 'Use config API instead');
284
-        static::config()->set('to_email_address', $to);
285
-    }
286
-
287
-    /**
288
-     * @deprecated
289
-     * @return null|string
290
-     */
291
-    public static function get_to_email_address()
292
-    {
293
-        Deprecation::notice('2.0', 'Use config API instead');
294
-        return static::config()->get('to_email_address');
295
-    }
296
-
297
-    /**
298
-     * @deprecated
299
-     * @param bool $results
300
-     */
301
-    public static function set_email_results($results)
302
-    {
303
-        Deprecation::notice('2.0', 'Use config API instead');
304
-        static::config()->set('email_results', $results);
305
-    }
306
-
307
-    /**
308
-     * @deprecated
309
-     * @return bool
310
-     */
311
-    public static function get_email_results()
312
-    {
313
-        Deprecation::notice('2.0', 'Use config API instead');
314
-        return static::config()->get('email_results');
315
-    }
27
+	/**
28
+	 * @var array
29
+	 */
30
+	private static $url_handlers = [
31
+		'' => 'index',
32
+	];
33
+
34
+	/**
35
+	 * @var string
36
+	 */
37
+	protected $checkSuiteName;
38
+
39
+	/**
40
+	 * @var string
41
+	 */
42
+	protected $title;
43
+
44
+	/**
45
+	 * @var int
46
+	 */
47
+	protected $errorCode = 500;
48
+
49
+	/**
50
+	 * @var null|string
51
+	 */
52
+	private static $to_email_address = null;
53
+
54
+	/**
55
+	 * @var null|string
56
+	 */
57
+	private static $from_email_address = null;
58
+
59
+	/**
60
+	 * @var bool
61
+	 */
62
+	private static $email_results = false;
63
+
64
+	/**
65
+	 * @var bool Log results via {@link \Psr\Log\LoggerInterface}
66
+	 */
67
+	private static $log_results_warning = false;
68
+
69
+	/**
70
+	 * @var string Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::WARNING
71
+	 */
72
+	private static $log_results_warning_level = LogLevel::WARNING;
73
+
74
+	/**
75
+	 * @var bool Log results via a {@link \Psr\Log\LoggerInterface}
76
+	 */
77
+	private static $log_results_error = false;
78
+
79
+	/**
80
+	 * @var int Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::ALERT
81
+	 */
82
+	private static $log_results_error_level = LogLevel::ALERT;
83
+
84
+	/**
85
+	 * @param string $checkSuiteName
86
+	 * @param string $title
87
+	 */
88
+	public function __construct($checkSuiteName, $title)
89
+	{
90
+		parent::__construct();
91
+
92
+		$this->checkSuiteName = $checkSuiteName;
93
+		$this->title = $title;
94
+	}
95
+
96
+	/**
97
+	 * @param string $permission
98
+	 *
99
+	 * @throws HTTPResponse_Exception
100
+	 */
101
+	public function init($permission = 'ADMIN')
102
+	{
103
+		// if the environment supports it, provide a basic auth challenge and see if it matches configured credentials
104
+		if (Environment::getEnv('ENVCHECK_BASICAUTH_USERNAME')
105
+			&& Environment::getEnv('ENVCHECK_BASICAUTH_PASSWORD')
106
+		) {
107
+			if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
108
+				// authenticate the input user/pass with the configured credentials
109
+				if (!(
110
+						$_SERVER['PHP_AUTH_USER'] == Environment::getEnv('ENVCHECK_BASICAUTH_USERNAME')
111
+						&& $_SERVER['PHP_AUTH_PW'] == Environment::getEnv('ENVCHECK_BASICAUTH_PASSWORD')
112
+					)
113
+				) {
114
+					$response = new HTTPResponse(null, 401);
115
+					$response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
116
+					// Exception is caught by RequestHandler->handleRequest() and will halt further execution
117
+					$e = new HTTPResponse_Exception(null, 401);
118
+					$e->setResponse($response);
119
+					throw $e;
120
+				}
121
+			} else {
122
+				$response = new HTTPResponse(null, 401);
123
+				$response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
124
+				// Exception is caught by RequestHandler->handleRequest() and will halt further execution
125
+				$e = new HTTPResponse_Exception(null, 401);
126
+				$e->setResponse($response);
127
+				throw $e;
128
+			}
129
+		} else {
130
+			if (!$this->canAccess(null, $permission)) {
131
+				return $this->httpError(403);
132
+			}
133
+		}
134
+	}
135
+
136
+	/**
137
+	 * @param null|int|Member $member
138
+	 * @param string $permission
139
+	 *
140
+	 * @return bool
141
+	 *
142
+	 * @throws HTTPResponse_Exception
143
+	 */
144
+	public function canAccess($member = null, $permission = 'ADMIN')
145
+	{
146
+		if (!$member) {
147
+			$member = Security::getCurrentUser();
148
+		}
149
+
150
+		if (!$member) {
151
+			$member = BasicAuth::requireLogin($this->getRequest(), 'Environment Checker', $permission, false);
152
+		}
153
+
154
+		// We allow access to this controller regardless of live-status or ADMIN permission only
155
+		// if on CLI.  Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
156
+		if (Director::isDev()
157
+			|| Director::is_cli()
158
+			|| empty($permission)
159
+			|| Permission::checkMember($member, $permission)
160
+		) {
161
+			return true;
162
+		}
163
+
164
+		// Extended access checks.
165
+		// "Veto" style, return NULL to abstain vote.
166
+		$canExtended = null;
167
+		$results = $this->extend('canAccess', $member);
168
+		if ($results && is_array($results)) {
169
+			if (!min($results)) {
170
+				return false;
171
+			}
172
+			return true;
173
+		}
174
+
175
+		return false;
176
+	}
177
+
178
+	/**
179
+	 * @return HTTPResponse
180
+	 */
181
+	public function index()
182
+	{
183
+		$response = new HTTPResponse;
184
+		$result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run();
185
+
186
+		if (!$result->ShouldPass()) {
187
+			$response->setStatusCode($this->errorCode);
188
+		}
189
+
190
+		$resultText = $result->customise([
191
+			'URL' => Director::absoluteBaseURL(),
192
+			'Title' => $this->title,
193
+			'Name' => $this->checkSuiteName,
194
+			'ErrorCode' => $this->errorCode,
195
+		])->renderWith(__CLASS__);
196
+
197
+		if ($this->config()->get('email_results') && !$result->ShouldPass()) {
198
+			$email = new Email(
199
+				$this->config()->get('from_email_address'),
200
+				$this->config()->get('to_email_address'),
201
+				$this->title,
202
+				$resultText
203
+			);
204
+			$email->send();
205
+		}
206
+
207
+		// Optionally log errors and warnings individually
208
+		foreach ($result->Details() as $detail) {
209
+			if ($this->config()->get('log_results_warning') && $detail->StatusCode == EnvironmentCheck::WARNING) {
210
+				$this->log(
211
+					sprintf('EnvironmentChecker warning at "%s" check. Message: %s', $detail->Check, $detail->Message),
212
+					$this->config()->get('log_results_warning_level')
213
+				);
214
+			} elseif ($this->config()->get('log_results_error') && $detail->StatusCode == EnvironmentCheck::ERROR) {
215
+				$this->log(
216
+					sprintf('EnvironmentChecker error at "%s" check. Message: %s', $detail->Check, $detail->Message),
217
+					$this->config()->get('log_results_error_level')
218
+				);
219
+			}
220
+		}
221
+
222
+		// output the result as JSON if requested
223
+		if ($this->getRequest()->getExtension() == 'json'
224
+			|| strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false
225
+		) {
226
+			$response->setBody($result->toJSON());
227
+			$response->addHeader('Content-Type', 'application/json');
228
+			return $response;
229
+		}
230
+
231
+		$response->setBody($resultText);
232
+
233
+		return $response;
234
+	}
235
+
236
+	/**
237
+	 * Sends a log entry to the configured PSR-3 LoggerInterface
238
+	 *
239
+	 * @param string $message
240
+	 * @param int $level
241
+	 */
242
+	public function log($message, $level)
243
+	{
244
+		Injector::inst()->get(LoggerInterface::class)->log($level, $message);
245
+	}
246
+
247
+	/**
248
+	 * Set the HTTP status code that should be returned when there's an error.
249
+	 *
250
+	 * @param int $errorCode
251
+	 */
252
+	public function setErrorCode($errorCode)
253
+	{
254
+		$this->errorCode = $errorCode;
255
+	}
256
+
257
+	/**
258
+	 * @deprecated
259
+	 * @param string $from
260
+	 */
261
+	public static function set_from_email_address($from)
262
+	{
263
+		Deprecation::notice('2.0', 'Use config API instead');
264
+		static::config()->set('from_email_address', $from);
265
+	}
266
+
267
+	/**
268
+	 * @deprecated
269
+	 * @return null|string
270
+	 */
271
+	public static function get_from_email_address()
272
+	{
273
+		Deprecation::notice('2.0', 'Use config API instead');
274
+		return static::config()->get('from_email_address');
275
+	}
276
+
277
+	/**
278
+	 * @deprecated
279
+	 * @param string $to
280
+	 */
281
+	public static function set_to_email_address($to)
282
+	{
283
+		Deprecation::notice('2.0', 'Use config API instead');
284
+		static::config()->set('to_email_address', $to);
285
+	}
286
+
287
+	/**
288
+	 * @deprecated
289
+	 * @return null|string
290
+	 */
291
+	public static function get_to_email_address()
292
+	{
293
+		Deprecation::notice('2.0', 'Use config API instead');
294
+		return static::config()->get('to_email_address');
295
+	}
296
+
297
+	/**
298
+	 * @deprecated
299
+	 * @param bool $results
300
+	 */
301
+	public static function set_email_results($results)
302
+	{
303
+		Deprecation::notice('2.0', 'Use config API instead');
304
+		static::config()->set('email_results', $results);
305
+	}
306
+
307
+	/**
308
+	 * @deprecated
309
+	 * @return bool
310
+	 */
311
+	public static function get_email_results()
312
+	{
313
+		Deprecation::notice('2.0', 'Use config API instead');
314
+		return static::config()->get('email_results');
315
+	}
316 316
 }
Please login to merge, or discard this patch.
src/Checks/SolrIndexCheck.php 2 patches
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -15,38 +15,38 @@
 block discarded – undo
15 15
  */
16 16
 class SolrIndexCheck implements EnvironmentCheck
17 17
 {
18
-    /**
19
-     * {@inheritDoc}
20
-     *
21
-     * @return array
22
-     */
23
-    public function check()
24
-    {
25
-        $brokenCores = [];
18
+	/**
19
+	 * {@inheritDoc}
20
+	 *
21
+	 * @return array
22
+	 */
23
+	public function check()
24
+	{
25
+		$brokenCores = [];
26 26
 
27
-        if (!class_exists(Solr::class)) {
28
-            return [
29
-                EnvironmentCheck::ERROR,
30
-                'Class `' . Solr::class . '` not found. Is the fulltextsearch module installed?'
31
-            ];
32
-        }
27
+		if (!class_exists(Solr::class)) {
28
+			return [
29
+				EnvironmentCheck::ERROR,
30
+				'Class `' . Solr::class . '` not found. Is the fulltextsearch module installed?'
31
+			];
32
+		}
33 33
 
34
-        $service = Solr::service();
35
-        foreach (Solr::get_indexes() as $index) {
36
-            /** @var SolrIndex $core */
37
-            $core = $index->getIndexName();
38
-            if (!$service->coreIsActive($core)) {
39
-                $brokenCores[] = $core;
40
-            }
41
-        }
34
+		$service = Solr::service();
35
+		foreach (Solr::get_indexes() as $index) {
36
+			/** @var SolrIndex $core */
37
+			$core = $index->getIndexName();
38
+			if (!$service->coreIsActive($core)) {
39
+				$brokenCores[] = $core;
40
+			}
41
+		}
42 42
 
43
-        if (!empty($brokenCores)) {
44
-            return [
45
-                EnvironmentCheck::ERROR,
46
-                'The following indexes are unavailable: ' . implode($brokenCores, ', ')
47
-            ];
48
-        }
43
+		if (!empty($brokenCores)) {
44
+			return [
45
+				EnvironmentCheck::ERROR,
46
+				'The following indexes are unavailable: ' . implode($brokenCores, ', ')
47
+			];
48
+		}
49 49
 
50
-        return [EnvironmentCheck::OK, 'Expected indexes are available.'];
51
-    }
50
+		return [EnvironmentCheck::OK, 'Expected indexes are available.'];
51
+	}
52 52
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
         if (!class_exists(Solr::class)) {
28 28
             return [
29 29
                 EnvironmentCheck::ERROR,
30
-                'Class `' . Solr::class . '` not found. Is the fulltextsearch module installed?'
30
+                'Class `'.Solr::class.'` not found. Is the fulltextsearch module installed?'
31 31
             ];
32 32
         }
33 33
 
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
         if (!empty($brokenCores)) {
44 44
             return [
45 45
                 EnvironmentCheck::ERROR,
46
-                'The following indexes are unavailable: ' . implode($brokenCores, ', ')
46
+                'The following indexes are unavailable: '.implode($brokenCores, ', ')
47 47
             ];
48 48
         }
49 49
 
Please login to merge, or discard this patch.
src/Checks/EnvTypeCheck.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -13,28 +13,28 @@
 block discarded – undo
13 13
  */
14 14
 class EnvTypeCheck implements EnvironmentCheck
15 15
 {
16
-    /**
17
-     * Check the environment setting.
18
-     *
19
-     * @return array
20
-     */
21
-    public function check()
22
-    {
23
-        $envSetting = Director::get_environment_type();
24
-        switch ($envSetting) {
25
-            case 'live':
26
-                return [
27
-                    EnvironmentCheck::OK,
28
-                    "Env setting is 'live'",
29
-                ];
30
-            // Fallthrough
31
-            default:
32
-            case 'dev':
33
-            case 'test':
34
-                return [
35
-                    EnvironmentCheck::ERROR,
36
-                    "Env setting is '{$envSetting}' and may disclose information",
37
-                ];
38
-        }
39
-    }
16
+	/**
17
+	 * Check the environment setting.
18
+	 *
19
+	 * @return array
20
+	 */
21
+	public function check()
22
+	{
23
+		$envSetting = Director::get_environment_type();
24
+		switch ($envSetting) {
25
+			case 'live':
26
+				return [
27
+					EnvironmentCheck::OK,
28
+					"Env setting is 'live'",
29
+				];
30
+			// Fallthrough
31
+			default:
32
+			case 'dev':
33
+			case 'test':
34
+				return [
35
+					EnvironmentCheck::ERROR,
36
+					"Env setting is '{$envSetting}' and may disclose information",
37
+				];
38
+		}
39
+	}
40 40
 }
Please login to merge, or discard this patch.