Passed
Pull Request — master (#61)
by Damian
03:27
created
tests/Checks/CacheHeadersCheckTest.php 1 patch
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -15,87 +15,87 @@
 block discarded – undo
15 15
  */
16 16
 class CacheHeadersCheckTest extends SapphireTest
17 17
 {
18
-    /**
19
-     * Test that directives that must be included, are.
20
-     *
21
-     * @return void
22
-     */
23
-    public function testMustInclude()
24
-    {
25
-        // Create a mock and queue responses
26
-        $mock = new MockHandler([
27
-            new Response(200, ['Cache-Control' => 'must-revalidate', 'ETag' => '123']),
28
-            new Response(200, ['Cache-Control' =>'no-cache', 'ETag' => '123']),
29
-            new Response(200, ['ETag' => '123']),
30
-            new Response(200, ['Cache-Control' => 'must-revalidate, private', 'ETag' => '123']),
31
-        ]);
18
+	/**
19
+	 * Test that directives that must be included, are.
20
+	 *
21
+	 * @return void
22
+	 */
23
+	public function testMustInclude()
24
+	{
25
+		// Create a mock and queue responses
26
+		$mock = new MockHandler([
27
+			new Response(200, ['Cache-Control' => 'must-revalidate', 'ETag' => '123']),
28
+			new Response(200, ['Cache-Control' =>'no-cache', 'ETag' => '123']),
29
+			new Response(200, ['ETag' => '123']),
30
+			new Response(200, ['Cache-Control' => 'must-revalidate, private', 'ETag' => '123']),
31
+		]);
32 32
 
33
-        $handler = HandlerStack::create($mock);
34
-        $client = new Client(['handler' => $handler]);
33
+		$handler = HandlerStack::create($mock);
34
+		$client = new Client(['handler' => $handler]);
35 35
 
36
-        $cacheHeadersCheck = new CacheHeadersCheck('/', ['must-revalidate']);
37
-        $cacheHeadersCheck->client = $client;
36
+		$cacheHeadersCheck = new CacheHeadersCheck('/', ['must-revalidate']);
37
+		$cacheHeadersCheck->client = $client;
38 38
 
39
-        // Run checks for each response above
40
-        $this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
41
-        $this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
42
-        $this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
43
-        $this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
44
-    }
39
+		// Run checks for each response above
40
+		$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
41
+		$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
42
+		$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
43
+		$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
44
+	}
45 45
 
46
-    /**
47
-     * Test that directives that must be excluded, are.
48
-     *
49
-     * @return void
50
-     */
51
-    public function testMustExclude()
52
-    {
53
-        // Create a mock and queue responses
54
-        $mock = new MockHandler([
55
-            new Response(200, ['Cache-Control' => 'must-revalidate', 'ETag' => '123']),
56
-            new Response(200, ['Cache-Control' =>'no-cache', 'ETag' => '123']),
57
-            new Response(200, ['ETag' => '123']),
58
-            new Response(200, ['Cache-Control' =>'private, no-store', ' ETag' => '123']),
59
-        ]);
46
+	/**
47
+	 * Test that directives that must be excluded, are.
48
+	 *
49
+	 * @return void
50
+	 */
51
+	public function testMustExclude()
52
+	{
53
+		// Create a mock and queue responses
54
+		$mock = new MockHandler([
55
+			new Response(200, ['Cache-Control' => 'must-revalidate', 'ETag' => '123']),
56
+			new Response(200, ['Cache-Control' =>'no-cache', 'ETag' => '123']),
57
+			new Response(200, ['ETag' => '123']),
58
+			new Response(200, ['Cache-Control' =>'private, no-store', ' ETag' => '123']),
59
+		]);
60 60
 
61
-        $handler = HandlerStack::create($mock);
62
-        $client = new Client(['handler' => $handler]);
61
+		$handler = HandlerStack::create($mock);
62
+		$client = new Client(['handler' => $handler]);
63 63
 
64
-        $cacheHeadersCheck = new CacheHeadersCheck('/', [], ["no-store", "no-cache", "private"]);
65
-        $cacheHeadersCheck->client = $client;
64
+		$cacheHeadersCheck = new CacheHeadersCheck('/', [], ["no-store", "no-cache", "private"]);
65
+		$cacheHeadersCheck->client = $client;
66 66
 
67
-        // Run checks for each response above
68
-        $this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
69
-        $this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
70
-        $this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
71
-        $this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
72
-    }
67
+		// Run checks for each response above
68
+		$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
69
+		$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
70
+		$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
71
+		$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
72
+	}
73 73
 
74
-    /**
75
-     * Test that Etag header must exist in response.
76
-     *
77
-     * @return void
78
-     */
79
-    public function testEtag()
80
-    {
81
-        // Create a mock and queue responses
82
-        $mock = new MockHandler([
83
-            new Response(200, ['Cache-Control' => 'must-revalidate', 'ETag' => '123']),
84
-            new Response(200, ['Cache-Control' =>'no-cache']),
85
-            new Response(200, ['ETag' => '123']),
86
-            new Response(200, []),
87
-        ]);
74
+	/**
75
+	 * Test that Etag header must exist in response.
76
+	 *
77
+	 * @return void
78
+	 */
79
+	public function testEtag()
80
+	{
81
+		// Create a mock and queue responses
82
+		$mock = new MockHandler([
83
+			new Response(200, ['Cache-Control' => 'must-revalidate', 'ETag' => '123']),
84
+			new Response(200, ['Cache-Control' =>'no-cache']),
85
+			new Response(200, ['ETag' => '123']),
86
+			new Response(200, []),
87
+		]);
88 88
 
89
-        $handler = HandlerStack::create($mock);
90
-        $client = new Client(['handler' => $handler]);
89
+		$handler = HandlerStack::create($mock);
90
+		$client = new Client(['handler' => $handler]);
91 91
 
92
-        $cacheHeadersCheck = new CacheHeadersCheck('/');
93
-        $cacheHeadersCheck->client = $client;
92
+		$cacheHeadersCheck = new CacheHeadersCheck('/');
93
+		$cacheHeadersCheck->client = $client;
94 94
 
95
-        // Run checks for each response above
96
-        $this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
97
-        $this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
98
-        $this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
99
-        $this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
100
-    }
95
+		// Run checks for each response above
96
+		$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
97
+		$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
98
+		$this->assertContains(EnvironmentCheck::OK, $cacheHeadersCheck->check());
99
+		$this->assertContains(EnvironmentCheck::ERROR, $cacheHeadersCheck->check());
100
+	}
101 101
 }
Please login to merge, or discard this patch.
tests/Checks/SessionCheckTest.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -15,62 +15,62 @@
 block discarded – undo
15 15
  */
16 16
 class SessionCheckTest extends SapphireTest
17 17
 {
18
-    /**
19
-     * @var SilverStripe\EnvironmentCheck\Checks\SessionCheck
20
-     */
21
-    public $sessionCheck = null;
18
+	/**
19
+	 * @var SilverStripe\EnvironmentCheck\Checks\SessionCheck
20
+	 */
21
+	public $sessionCheck = null;
22 22
 
23
-    /**
24
-     * Create a session check for use by tests.
25
-     *
26
-     * @return void
27
-     */
28
-    protected function setUp()
29
-    {
30
-        parent::setUp();
31
-        $this->sessionCheck = new SessionCheck('/');
32
-    }
23
+	/**
24
+	 * Create a session check for use by tests.
25
+	 *
26
+	 * @return void
27
+	 */
28
+	protected function setUp()
29
+	{
30
+		parent::setUp();
31
+		$this->sessionCheck = new SessionCheck('/');
32
+	}
33 33
 
34
-    /**
35
-     * Env check reports error when session cookies are being set.
36
-     *
37
-     * @return void
38
-     */
39
-    public function testSessionSet()
40
-    {
41
-        // Create a mock and queue two responses.
42
-        $mock = new MockHandler([
43
-            new Response(200, ['Set-Cookie' => 'PHPSESSID:foo']),
44
-            new Response(200, ['Set-Cookie' => 'SECSESSID:bar'])
45
-        ]);
34
+	/**
35
+	 * Env check reports error when session cookies are being set.
36
+	 *
37
+	 * @return void
38
+	 */
39
+	public function testSessionSet()
40
+	{
41
+		// Create a mock and queue two responses.
42
+		$mock = new MockHandler([
43
+			new Response(200, ['Set-Cookie' => 'PHPSESSID:foo']),
44
+			new Response(200, ['Set-Cookie' => 'SECSESSID:bar'])
45
+		]);
46 46
 
47
-        $handler = HandlerStack::create($mock);
48
-        $client = new Client(['handler' => $handler]);
49
-        $this->sessionCheck->client = $client;
47
+		$handler = HandlerStack::create($mock);
48
+		$client = new Client(['handler' => $handler]);
49
+		$this->sessionCheck->client = $client;
50 50
 
51
-        // Check for PHPSESSID
52
-        $this->assertContains(EnvironmentCheck::ERROR, $this->sessionCheck->check());
51
+		// Check for PHPSESSID
52
+		$this->assertContains(EnvironmentCheck::ERROR, $this->sessionCheck->check());
53 53
 
54
-        // Check for SECSESSID
55
-        $this->assertContains(EnvironmentCheck::ERROR, $this->sessionCheck->check());
56
-    }
54
+		// Check for SECSESSID
55
+		$this->assertContains(EnvironmentCheck::ERROR, $this->sessionCheck->check());
56
+	}
57 57
 
58
-    /**
59
-     * Env check responds OK when no session cookies are set in response.
60
-     *
61
-     * @return void
62
-     */
63
-    public function testSessionNotSet()
64
-    {
65
-        // Create a mock and queue two responses.
66
-        $mock = new MockHandler([
67
-            new Response(200)
68
-        ]);
58
+	/**
59
+	 * Env check responds OK when no session cookies are set in response.
60
+	 *
61
+	 * @return void
62
+	 */
63
+	public function testSessionNotSet()
64
+	{
65
+		// Create a mock and queue two responses.
66
+		$mock = new MockHandler([
67
+			new Response(200)
68
+		]);
69 69
 
70
-        $handler = HandlerStack::create($mock);
71
-        $client = new Client(['handler' => $handler]);
72
-        $this->sessionCheck->client = $client;
70
+		$handler = HandlerStack::create($mock);
71
+		$client = new Client(['handler' => $handler]);
72
+		$this->sessionCheck->client = $client;
73 73
 
74
-        $this->assertContains(EnvironmentCheck::OK, $this->sessionCheck->check());
75
-    }
74
+		$this->assertContains(EnvironmentCheck::OK, $this->sessionCheck->check());
75
+	}
76 76
 }
Please login to merge, or discard this patch.
src/Services/ClientFactory.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -14,36 +14,36 @@
 block discarded – undo
14 14
  */
15 15
 class ClientFactory implements Factory
16 16
 {
17
-    use Configurable;
17
+	use Configurable;
18 18
 
19
-    /**
20
-     * Default config for Guzzle client.
21
-     *
22
-     * @var array
23
-     */
24
-    private static $default_config = [];
19
+	/**
20
+	 * Default config for Guzzle client.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	private static $default_config = [];
25 25
 
26
-    /**
27
-     * Wrapper to create a Guzzle client.
28
-     *
29
-     * {@inheritdoc}
30
-     */
31
-    public function create($service, array $params = [])
32
-    {
33
-        return new GuzzleClient($this->getConfig($params));
34
-    }
26
+	/**
27
+	 * Wrapper to create a Guzzle client.
28
+	 *
29
+	 * {@inheritdoc}
30
+	 */
31
+	public function create($service, array $params = [])
32
+	{
33
+		return new GuzzleClient($this->getConfig($params));
34
+	}
35 35
 
36
-    /**
37
-     * Merge config provided from yaml with default config
38
-     *
39
-     * @param array $overrides
40
-     * @return array
41
-     */
42
-    public function getConfig(array $overrides)
43
-    {
44
-        return array_merge(
45
-            $this->config()->get('default_config'),
46
-            $overrides
47
-        );
48
-    }
36
+	/**
37
+	 * Merge config provided from yaml with default config
38
+	 *
39
+	 * @param array $overrides
40
+	 * @return array
41
+	 */
42
+	public function getConfig(array $overrides)
43
+	{
44
+		return array_merge(
45
+			$this->config()->get('default_config'),
46
+			$overrides
47
+		);
48
+	}
49 49
 }
Please login to merge, or discard this patch.
src/Traits/Fetcher.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -11,41 +11,41 @@
 block discarded – undo
11 11
  */
12 12
 trait Fetcher
13 13
 {
14
-    /**
15
-     * Client for making requests, set vi Injector.
16
-     *
17
-     * @see SilverStripe\EnvironmentCheck\Services
18
-     *
19
-     * @var GuzzleHttp\Client
20
-     */
21
-    public $client = null;
14
+	/**
15
+	 * Client for making requests, set vi Injector.
16
+	 *
17
+	 * @see SilverStripe\EnvironmentCheck\Services
18
+	 *
19
+	 * @var GuzzleHttp\Client
20
+	 */
21
+	public $client = null;
22 22
 
23
-    /**
24
-     * Absolute URL for requests.
25
-     *
26
-     * @var string
27
-     */
28
-    protected $url;
23
+	/**
24
+	 * Absolute URL for requests.
25
+	 *
26
+	 * @var string
27
+	 */
28
+	protected $url;
29 29
 
30
-    /**
31
-     * Set URL for requests.
32
-     *
33
-     * @param string $url Relative URL
34
-     * @return self
35
-     */
36
-    public function setURL($url)
37
-    {
38
-        $this->url = Director::absoluteURL($url);
39
-        return $this;
40
-    }
30
+	/**
31
+	 * Set URL for requests.
32
+	 *
33
+	 * @param string $url Relative URL
34
+	 * @return self
35
+	 */
36
+	public function setURL($url)
37
+	{
38
+		$this->url = Director::absoluteURL($url);
39
+		return $this;
40
+	}
41 41
 
42
-    /**
43
-     * Getter for URL
44
-     *
45
-     * @return string
46
-     */
47
-    public function getURL()
48
-    {
49
-        return $this->url;
50
-    }
42
+	/**
43
+	 * Getter for URL
44
+	 *
45
+	 * @return string
46
+	 */
47
+	public function getURL()
48
+	{
49
+		return $this->url;
50
+	}
51 51
 }
Please login to merge, or discard this patch.
src/Controllers/DevCheckController.php 1 patch
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -14,39 +14,39 @@
 block discarded – undo
14 14
  */
15 15
 class DevCheckController extends Controller
16 16
 {
17
-    /**
18
-     * @var array
19
-     */
20
-    private static $allowed_actions = [
21
-        'index'
22
-    ];
23
-
24
-    /**
25
-     * Permission code to check for access to this controller.
26
-     *
27
-     * @var string
28
-     */
29
-    private static $permission = 'ADMIN';
30
-
31
-    /**
32
-     * @param HTTPRequest $request
33
-     *
34
-     * @return EnvironmentChecker
35
-     *
36
-     * @throws HTTPResponse_Exception
37
-     */
38
-    public function index($request)
39
-    {
40
-        $suite = 'check';
41
-
42
-        if ($name = $request->param('Suite')) {
43
-            $suite = $name;
44
-        }
45
-
46
-        $checker = new EnvironmentChecker($suite, 'Environment status');
47
-        $checker->setRequest($request);
48
-        $checker->init($this->config()->permission);
49
-
50
-        return $checker;
51
-    }
17
+	/**
18
+	 * @var array
19
+	 */
20
+	private static $allowed_actions = [
21
+		'index'
22
+	];
23
+
24
+	/**
25
+	 * Permission code to check for access to this controller.
26
+	 *
27
+	 * @var string
28
+	 */
29
+	private static $permission = 'ADMIN';
30
+
31
+	/**
32
+	 * @param HTTPRequest $request
33
+	 *
34
+	 * @return EnvironmentChecker
35
+	 *
36
+	 * @throws HTTPResponse_Exception
37
+	 */
38
+	public function index($request)
39
+	{
40
+		$suite = 'check';
41
+
42
+		if ($name = $request->param('Suite')) {
43
+			$suite = $name;
44
+		}
45
+
46
+		$checker = new EnvironmentChecker($suite, 'Environment status');
47
+		$checker->setRequest($request);
48
+		$checker->init($this->config()->permission);
49
+
50
+		return $checker;
51
+	}
52 52
 }
Please login to merge, or discard this patch.
src/EnvironmentChecker.php 1 patch
Indentation   +272 added lines, -272 removed lines patch added patch discarded remove patch
@@ -23,276 +23,276 @@
 block discarded – undo
23 23
  */
24 24
 class EnvironmentChecker extends RequestHandler
25 25
 {
26
-    /**
27
-     * @var array
28
-     */
29
-    private static $url_handlers = [
30
-        '' => 'index',
31
-    ];
32
-
33
-    /**
34
-     * @var string
35
-     */
36
-    protected $checkSuiteName;
37
-
38
-    /**
39
-     * @var string
40
-     */
41
-    protected $title;
42
-
43
-    /**
44
-     * @var int
45
-     */
46
-    protected $errorCode = 500;
47
-
48
-    /**
49
-     * @var null|string
50
-     */
51
-    private static $to_email_address = null;
52
-
53
-    /**
54
-     * @var null|string
55
-     */
56
-    private static $from_email_address = null;
57
-
58
-    /**
59
-     * @var bool
60
-     */
61
-    private static $email_results = false;
62
-
63
-    /**
64
-     * @var bool Log results via {@link \Psr\Log\LoggerInterface}
65
-     */
66
-    private static $log_results_warning = false;
67
-
68
-    /**
69
-     * @var string Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::WARNING
70
-     */
71
-    private static $log_results_warning_level = LogLevel::WARNING;
72
-
73
-    /**
74
-     * @var bool Log results via a {@link \Psr\Log\LoggerInterface}
75
-     */
76
-    private static $log_results_error = false;
77
-
78
-    /**
79
-     * @var int Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::ALERT
80
-     */
81
-    private static $log_results_error_level = LogLevel::ALERT;
82
-
83
-    /**
84
-     * @param string $checkSuiteName
85
-     * @param string $title
86
-     */
87
-    public function __construct($checkSuiteName, $title)
88
-    {
89
-        parent::__construct();
90
-
91
-        $this->checkSuiteName = $checkSuiteName;
92
-        $this->title = $title;
93
-    }
94
-
95
-    /**
96
-     * @param string $permission
97
-     *
98
-     * @throws HTTPResponse_Exception
99
-     */
100
-    public function init($permission = 'ADMIN')
101
-    {
102
-        // if the environment supports it, provide a basic auth challenge and see if it matches configured credentials
103
-        if (Environment::getEnv('ENVCHECK_BASICAUTH_USERNAME')
104
-            && Environment::getEnv('ENVCHECK_BASICAUTH_PASSWORD')
105
-        ) {
106
-            // Check that details are both provided, and match
107
-            if (empty($_SERVER['PHP_AUTH_USER']) || empty($_SERVER['PHP_AUTH_PW'])
108
-                || $_SERVER['PHP_AUTH_USER'] != Environment::getEnv('ENVCHECK_BASICAUTH_USERNAME')
109
-                || $_SERVER['PHP_AUTH_PW'] != Environment::getEnv('ENVCHECK_BASICAUTH_PASSWORD')
110
-            ) {
111
-                // Fail check with basic auth challenge
112
-                $response = new HTTPResponse(null, 401);
113
-                $response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
114
-                throw new HTTPResponse_Exception($response);
115
-            }
116
-        } elseif (!$this->canAccess(null, $permission)) {
117
-            // Fail check with silverstripe login challenge
118
-            $result = Security::permissionFailure($this, "You must have the {$permission} permission to access this check");
119
-            throw new HTTPResponse_Exception($result);
120
-        }
121
-    }
122
-
123
-    /**
124
-     * Determine if the current member can access the environment checker
125
-     *
126
-     * @param null|int|Member $member
127
-     * @param string          $permission
128
-     * @return bool
129
-     */
130
-    public function canAccess($member = null, $permission = 'ADMIN')
131
-    {
132
-        if (!$member) {
133
-            $member = Security::getCurrentUser();
134
-        }
135
-
136
-        // We allow access to this controller regardless of live-status or ADMIN permission only
137
-        // if on CLI.  Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
138
-        if (Director::isDev()
139
-            || Director::is_cli()
140
-            || empty($permission)
141
-            || Permission::checkMember($member, $permission)
142
-        ) {
143
-            return true;
144
-        }
145
-
146
-        // Extended access checks.
147
-        // "Veto" style, return NULL to abstain vote.
148
-        $canExtended = null;
149
-        $results = $this->extend('canAccess', $member);
150
-        if ($results && is_array($results)) {
151
-            if (!min($results)) {
152
-                return false;
153
-            }
154
-            return true;
155
-        }
156
-
157
-        return false;
158
-    }
159
-
160
-    /**
161
-     * @return HTTPResponse
162
-     */
163
-    public function index()
164
-    {
165
-        $response = new HTTPResponse;
166
-        $result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run();
167
-
168
-        if (!$result->ShouldPass()) {
169
-            $response->setStatusCode($this->errorCode);
170
-        }
171
-
172
-        $resultText = $result->customise([
173
-            'URL'       => Director::absoluteBaseURL(),
174
-            'Title'     => $this->title,
175
-            'Name'      => $this->checkSuiteName,
176
-            'ErrorCode' => $this->errorCode,
177
-        ])->renderWith(__CLASS__);
178
-
179
-        if ($this->config()->get('email_results') && !$result->ShouldPass()) {
180
-            $email = new Email(
181
-                $this->config()->get('from_email_address'),
182
-                $this->config()->get('to_email_address'),
183
-                $this->title,
184
-                $resultText
185
-            );
186
-            $email->send();
187
-        }
188
-
189
-        // Optionally log errors and warnings individually
190
-        foreach ($result->Details() as $detail) {
191
-            if ($this->config()->get('log_results_warning') && $detail->StatusCode == EnvironmentCheck::WARNING) {
192
-                $this->log(
193
-                    sprintf('EnvironmentChecker warning at "%s" check. Message: %s', $detail->Check, $detail->Message),
194
-                    $this->config()->get('log_results_warning_level')
195
-                );
196
-            } elseif ($this->config()->get('log_results_error') && $detail->StatusCode == EnvironmentCheck::ERROR) {
197
-                $this->log(
198
-                    sprintf('EnvironmentChecker error at "%s" check. Message: %s', $detail->Check, $detail->Message),
199
-                    $this->config()->get('log_results_error_level')
200
-                );
201
-            }
202
-        }
203
-
204
-        // output the result as JSON if requested
205
-        if ($this->getRequest()->getExtension() == 'json'
206
-            || strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false
207
-        ) {
208
-            $response->setBody($result->toJSON());
209
-            $response->addHeader('Content-Type', 'application/json');
210
-            return $response;
211
-        }
212
-
213
-        $response->setBody($resultText);
214
-
215
-        return $response;
216
-    }
217
-
218
-    /**
219
-     * Sends a log entry to the configured PSR-3 LoggerInterface
220
-     *
221
-     * @param string $message
222
-     * @param int    $level
223
-     */
224
-    public function log($message, $level)
225
-    {
226
-        Injector::inst()->get(LoggerInterface::class)->log($level, $message);
227
-    }
228
-
229
-    /**
230
-     * Set the HTTP status code that should be returned when there's an error.
231
-     *
232
-     * @param int $errorCode
233
-     */
234
-    public function setErrorCode($errorCode)
235
-    {
236
-        $this->errorCode = $errorCode;
237
-    }
238
-
239
-    /**
240
-     * @deprecated
241
-     * @param string $from
242
-     */
243
-    public static function set_from_email_address($from)
244
-    {
245
-        Deprecation::notice('2.0', 'Use config API instead');
246
-        static::config()->set('from_email_address', $from);
247
-    }
248
-
249
-    /**
250
-     * @deprecated
251
-     * @return null|string
252
-     */
253
-    public static function get_from_email_address()
254
-    {
255
-        Deprecation::notice('2.0', 'Use config API instead');
256
-        return static::config()->get('from_email_address');
257
-    }
258
-
259
-    /**
260
-     * @deprecated
261
-     * @param string $to
262
-     */
263
-    public static function set_to_email_address($to)
264
-    {
265
-        Deprecation::notice('2.0', 'Use config API instead');
266
-        static::config()->set('to_email_address', $to);
267
-    }
268
-
269
-    /**
270
-     * @deprecated
271
-     * @return null|string
272
-     */
273
-    public static function get_to_email_address()
274
-    {
275
-        Deprecation::notice('2.0', 'Use config API instead');
276
-        return static::config()->get('to_email_address');
277
-    }
278
-
279
-    /**
280
-     * @deprecated
281
-     * @param bool $results
282
-     */
283
-    public static function set_email_results($results)
284
-    {
285
-        Deprecation::notice('2.0', 'Use config API instead');
286
-        static::config()->set('email_results', $results);
287
-    }
288
-
289
-    /**
290
-     * @deprecated
291
-     * @return bool
292
-     */
293
-    public static function get_email_results()
294
-    {
295
-        Deprecation::notice('2.0', 'Use config API instead');
296
-        return static::config()->get('email_results');
297
-    }
26
+	/**
27
+	 * @var array
28
+	 */
29
+	private static $url_handlers = [
30
+		'' => 'index',
31
+	];
32
+
33
+	/**
34
+	 * @var string
35
+	 */
36
+	protected $checkSuiteName;
37
+
38
+	/**
39
+	 * @var string
40
+	 */
41
+	protected $title;
42
+
43
+	/**
44
+	 * @var int
45
+	 */
46
+	protected $errorCode = 500;
47
+
48
+	/**
49
+	 * @var null|string
50
+	 */
51
+	private static $to_email_address = null;
52
+
53
+	/**
54
+	 * @var null|string
55
+	 */
56
+	private static $from_email_address = null;
57
+
58
+	/**
59
+	 * @var bool
60
+	 */
61
+	private static $email_results = false;
62
+
63
+	/**
64
+	 * @var bool Log results via {@link \Psr\Log\LoggerInterface}
65
+	 */
66
+	private static $log_results_warning = false;
67
+
68
+	/**
69
+	 * @var string Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::WARNING
70
+	 */
71
+	private static $log_results_warning_level = LogLevel::WARNING;
72
+
73
+	/**
74
+	 * @var bool Log results via a {@link \Psr\Log\LoggerInterface}
75
+	 */
76
+	private static $log_results_error = false;
77
+
78
+	/**
79
+	 * @var int Maps to {@link \Psr\Log\LogLevel} levels. Defaults to LogLevel::ALERT
80
+	 */
81
+	private static $log_results_error_level = LogLevel::ALERT;
82
+
83
+	/**
84
+	 * @param string $checkSuiteName
85
+	 * @param string $title
86
+	 */
87
+	public function __construct($checkSuiteName, $title)
88
+	{
89
+		parent::__construct();
90
+
91
+		$this->checkSuiteName = $checkSuiteName;
92
+		$this->title = $title;
93
+	}
94
+
95
+	/**
96
+	 * @param string $permission
97
+	 *
98
+	 * @throws HTTPResponse_Exception
99
+	 */
100
+	public function init($permission = 'ADMIN')
101
+	{
102
+		// if the environment supports it, provide a basic auth challenge and see if it matches configured credentials
103
+		if (Environment::getEnv('ENVCHECK_BASICAUTH_USERNAME')
104
+			&& Environment::getEnv('ENVCHECK_BASICAUTH_PASSWORD')
105
+		) {
106
+			// Check that details are both provided, and match
107
+			if (empty($_SERVER['PHP_AUTH_USER']) || empty($_SERVER['PHP_AUTH_PW'])
108
+				|| $_SERVER['PHP_AUTH_USER'] != Environment::getEnv('ENVCHECK_BASICAUTH_USERNAME')
109
+				|| $_SERVER['PHP_AUTH_PW'] != Environment::getEnv('ENVCHECK_BASICAUTH_PASSWORD')
110
+			) {
111
+				// Fail check with basic auth challenge
112
+				$response = new HTTPResponse(null, 401);
113
+				$response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
114
+				throw new HTTPResponse_Exception($response);
115
+			}
116
+		} elseif (!$this->canAccess(null, $permission)) {
117
+			// Fail check with silverstripe login challenge
118
+			$result = Security::permissionFailure($this, "You must have the {$permission} permission to access this check");
119
+			throw new HTTPResponse_Exception($result);
120
+		}
121
+	}
122
+
123
+	/**
124
+	 * Determine if the current member can access the environment checker
125
+	 *
126
+	 * @param null|int|Member $member
127
+	 * @param string          $permission
128
+	 * @return bool
129
+	 */
130
+	public function canAccess($member = null, $permission = 'ADMIN')
131
+	{
132
+		if (!$member) {
133
+			$member = Security::getCurrentUser();
134
+		}
135
+
136
+		// We allow access to this controller regardless of live-status or ADMIN permission only
137
+		// if on CLI.  Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
138
+		if (Director::isDev()
139
+			|| Director::is_cli()
140
+			|| empty($permission)
141
+			|| Permission::checkMember($member, $permission)
142
+		) {
143
+			return true;
144
+		}
145
+
146
+		// Extended access checks.
147
+		// "Veto" style, return NULL to abstain vote.
148
+		$canExtended = null;
149
+		$results = $this->extend('canAccess', $member);
150
+		if ($results && is_array($results)) {
151
+			if (!min($results)) {
152
+				return false;
153
+			}
154
+			return true;
155
+		}
156
+
157
+		return false;
158
+	}
159
+
160
+	/**
161
+	 * @return HTTPResponse
162
+	 */
163
+	public function index()
164
+	{
165
+		$response = new HTTPResponse;
166
+		$result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run();
167
+
168
+		if (!$result->ShouldPass()) {
169
+			$response->setStatusCode($this->errorCode);
170
+		}
171
+
172
+		$resultText = $result->customise([
173
+			'URL'       => Director::absoluteBaseURL(),
174
+			'Title'     => $this->title,
175
+			'Name'      => $this->checkSuiteName,
176
+			'ErrorCode' => $this->errorCode,
177
+		])->renderWith(__CLASS__);
178
+
179
+		if ($this->config()->get('email_results') && !$result->ShouldPass()) {
180
+			$email = new Email(
181
+				$this->config()->get('from_email_address'),
182
+				$this->config()->get('to_email_address'),
183
+				$this->title,
184
+				$resultText
185
+			);
186
+			$email->send();
187
+		}
188
+
189
+		// Optionally log errors and warnings individually
190
+		foreach ($result->Details() as $detail) {
191
+			if ($this->config()->get('log_results_warning') && $detail->StatusCode == EnvironmentCheck::WARNING) {
192
+				$this->log(
193
+					sprintf('EnvironmentChecker warning at "%s" check. Message: %s', $detail->Check, $detail->Message),
194
+					$this->config()->get('log_results_warning_level')
195
+				);
196
+			} elseif ($this->config()->get('log_results_error') && $detail->StatusCode == EnvironmentCheck::ERROR) {
197
+				$this->log(
198
+					sprintf('EnvironmentChecker error at "%s" check. Message: %s', $detail->Check, $detail->Message),
199
+					$this->config()->get('log_results_error_level')
200
+				);
201
+			}
202
+		}
203
+
204
+		// output the result as JSON if requested
205
+		if ($this->getRequest()->getExtension() == 'json'
206
+			|| strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false
207
+		) {
208
+			$response->setBody($result->toJSON());
209
+			$response->addHeader('Content-Type', 'application/json');
210
+			return $response;
211
+		}
212
+
213
+		$response->setBody($resultText);
214
+
215
+		return $response;
216
+	}
217
+
218
+	/**
219
+	 * Sends a log entry to the configured PSR-3 LoggerInterface
220
+	 *
221
+	 * @param string $message
222
+	 * @param int    $level
223
+	 */
224
+	public function log($message, $level)
225
+	{
226
+		Injector::inst()->get(LoggerInterface::class)->log($level, $message);
227
+	}
228
+
229
+	/**
230
+	 * Set the HTTP status code that should be returned when there's an error.
231
+	 *
232
+	 * @param int $errorCode
233
+	 */
234
+	public function setErrorCode($errorCode)
235
+	{
236
+		$this->errorCode = $errorCode;
237
+	}
238
+
239
+	/**
240
+	 * @deprecated
241
+	 * @param string $from
242
+	 */
243
+	public static function set_from_email_address($from)
244
+	{
245
+		Deprecation::notice('2.0', 'Use config API instead');
246
+		static::config()->set('from_email_address', $from);
247
+	}
248
+
249
+	/**
250
+	 * @deprecated
251
+	 * @return null|string
252
+	 */
253
+	public static function get_from_email_address()
254
+	{
255
+		Deprecation::notice('2.0', 'Use config API instead');
256
+		return static::config()->get('from_email_address');
257
+	}
258
+
259
+	/**
260
+	 * @deprecated
261
+	 * @param string $to
262
+	 */
263
+	public static function set_to_email_address($to)
264
+	{
265
+		Deprecation::notice('2.0', 'Use config API instead');
266
+		static::config()->set('to_email_address', $to);
267
+	}
268
+
269
+	/**
270
+	 * @deprecated
271
+	 * @return null|string
272
+	 */
273
+	public static function get_to_email_address()
274
+	{
275
+		Deprecation::notice('2.0', 'Use config API instead');
276
+		return static::config()->get('to_email_address');
277
+	}
278
+
279
+	/**
280
+	 * @deprecated
281
+	 * @param bool $results
282
+	 */
283
+	public static function set_email_results($results)
284
+	{
285
+		Deprecation::notice('2.0', 'Use config API instead');
286
+		static::config()->set('email_results', $results);
287
+	}
288
+
289
+	/**
290
+	 * @deprecated
291
+	 * @return bool
292
+	 */
293
+	public static function get_email_results()
294
+	{
295
+		Deprecation::notice('2.0', 'Use config API instead');
296
+		return static::config()->get('email_results');
297
+	}
298 298
 }
Please login to merge, or discard this patch.