Completed
Branch master (9dcfc4)
by Daniel
24:32
created
src/Checks/FileAccessibilityAndValidationCheck.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -74,7 +74,7 @@
 block discarded – undo
74 74
     /**
75 75
      * {@inheritDoc}
76 76
      *
77
-     * @return array
77
+     * @return string[]
78 78
      */
79 79
     public function check()
80 80
     {
Please login to merge, or discard this patch.
Indentation   +166 added lines, -166 removed lines patch added patch discarded remove patch
@@ -28,170 +28,170 @@
 block discarded – undo
28 28
  */
29 29
 class FileAccessibilityAndValidationCheck implements EnvironmentCheck
30 30
 {
31
-    /**
32
-     * @var int
33
-     */
34
-    const CHECK_SINGLE = 1;
35
-
36
-    /**
37
-     * @var int
38
-     */
39
-    const CHECK_ALL = 2;
40
-
41
-    /**
42
-     * Absolute path to a file or folder, compatible with glob().
43
-     *
44
-     * @var string
45
-     */
46
-    protected $path;
47
-
48
-    /**
49
-     * Constant, check for a single file to match age criteria, or all of them.
50
-     *
51
-     * @var int
52
-     */
53
-    protected $fileTypeValidateFunc;
54
-
55
-    /**
56
-     * Constant, check for a single file to match age criteria, or all of them.
57
-     *
58
-     * @var int
59
-     */
60
-    protected $checkType;
61
-
62
-    /**
63
-     * @param string $path
64
-     * @param string $fileTypeValidateFunc
65
-     * @param null|int $checkType
66
-     */
67
-    public function __construct($path, $fileTypeValidateFunc = 'noVidation', $checkType = null)
68
-    {
69
-        $this->path = $path;
70
-        $this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc : 'noVidation';
71
-        $this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
72
-    }
73
-
74
-    /**
75
-     * {@inheritDoc}
76
-     *
77
-     * @return array
78
-     */
79
-    public function check()
80
-    {
81
-        $origStage = Versioned::get_reading_mode();
82
-        Versioned::set_reading_mode(Versioned::LIVE);
83
-
84
-        $files = $this->getFiles();
85
-        if ($files) {
86
-            $fileTypeValidateFunc = $this->fileTypeValidateFunc;
87
-            if (method_exists($this, $fileTypeValidateFunc)) {
88
-                $invalidFiles = [];
89
-                $validFiles = [];
90
-
91
-                foreach ($files as $file) {
92
-                    if ($this->$fileTypeValidateFunc($file)) {
93
-                        $validFiles[] = $file;
94
-                    } else {
95
-                        $invalidFiles[] = $file;
96
-                    }
97
-                }
98
-
99
-                // If at least one file was valid, count as passed
100
-                if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
101
-                    $validFileList = PHP_EOL;
102
-                    foreach ($validFiles as $vf) {
103
-                        $validFileList .= $vf . PHP_EOL;
104
-                    }
105
-                    if ($fileTypeValidateFunc == 'noVidation') {
106
-                        $checkReturn = [
107
-                            EnvironmentCheck::OK,
108
-                            sprintf('At least these file(s) accessible: %s', $validFileList)
109
-                        ];
110
-                    } else {
111
-                        $checkReturn = [
112
-                            EnvironmentCheck::OK,
113
-                            sprintf(
114
-                                'At least these file(s) passed file type validate function "%s": %s',
115
-                                $fileTypeValidateFunc,
116
-                                $validFileList
117
-                            )
118
-                        ];
119
-                    }
120
-                } else {
121
-                    if (count($invalidFiles) == 0) {
122
-                        $checkReturn = [EnvironmentCheck::OK, 'All files valideted'];
123
-                    } else {
124
-                        $invalidFileList = PHP_EOL;
125
-                        foreach ($invalidFiles as $vf) {
126
-                            $invalidFileList .= $vf . PHP_EOL;
127
-                        }
128
-
129
-                        if ($fileTypeValidateFunc == 'noVidation') {
130
-                            $checkReturn = [
131
-                                EnvironmentCheck::ERROR,
132
-                                sprintf('File(s) not accessible: %s', $invalidFileList)
133
-                            ];
134
-                        } else {
135
-                            $checkReturn = [
136
-                                EnvironmentCheck::ERROR,
137
-                                sprintf(
138
-                                    'File(s) not passing the file type validate function "%s": %s',
139
-                                    $fileTypeValidateFunc,
140
-                                    $invalidFileList
141
-                                )
142
-                            ];
143
-                        }
144
-                    }
145
-                }
146
-            } else {
147
-                $checkReturn =  array(
148
-                    EnvironmentCheck::ERROR,
149
-                    sprintf("Invalid file type validation method name passed: %s ", $fileTypeValidateFunc)
150
-                );
151
-            }
152
-        } else {
153
-            $checkReturn = array(
154
-                EnvironmentCheck::ERROR,
155
-                sprintf("No files accessible at path %s", $this->path)
156
-            );
157
-        }
158
-
159
-        Versioned::set_reading_mode($origStage);
160
-
161
-        return $checkReturn;
162
-    }
163
-
164
-    /**
165
-     * @param string $file
166
-     *
167
-     * @return bool
168
-     */
169
-    private function jsonValidate($file)
170
-    {
171
-        $json = json_decode(file_get_contents($file));
172
-        if (!$json) {
173
-            return false;
174
-        }
175
-        return true;
176
-    }
177
-
178
-    /**
179
-     * @param string $file
180
-     *
181
-     * @return bool
182
-     */
183
-    protected function noVidation($file)
184
-    {
185
-        return true;
186
-    }
187
-
188
-    /**
189
-     * Gets a list of absolute file paths.
190
-     *
191
-     * @return array
192
-     */
193
-    protected function getFiles()
194
-    {
195
-        return glob($this->path);
196
-    }
31
+	/**
32
+	 * @var int
33
+	 */
34
+	const CHECK_SINGLE = 1;
35
+
36
+	/**
37
+	 * @var int
38
+	 */
39
+	const CHECK_ALL = 2;
40
+
41
+	/**
42
+	 * Absolute path to a file or folder, compatible with glob().
43
+	 *
44
+	 * @var string
45
+	 */
46
+	protected $path;
47
+
48
+	/**
49
+	 * Constant, check for a single file to match age criteria, or all of them.
50
+	 *
51
+	 * @var int
52
+	 */
53
+	protected $fileTypeValidateFunc;
54
+
55
+	/**
56
+	 * Constant, check for a single file to match age criteria, or all of them.
57
+	 *
58
+	 * @var int
59
+	 */
60
+	protected $checkType;
61
+
62
+	/**
63
+	 * @param string $path
64
+	 * @param string $fileTypeValidateFunc
65
+	 * @param null|int $checkType
66
+	 */
67
+	public function __construct($path, $fileTypeValidateFunc = 'noVidation', $checkType = null)
68
+	{
69
+		$this->path = $path;
70
+		$this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc : 'noVidation';
71
+		$this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
72
+	}
73
+
74
+	/**
75
+	 * {@inheritDoc}
76
+	 *
77
+	 * @return array
78
+	 */
79
+	public function check()
80
+	{
81
+		$origStage = Versioned::get_reading_mode();
82
+		Versioned::set_reading_mode(Versioned::LIVE);
83
+
84
+		$files = $this->getFiles();
85
+		if ($files) {
86
+			$fileTypeValidateFunc = $this->fileTypeValidateFunc;
87
+			if (method_exists($this, $fileTypeValidateFunc)) {
88
+				$invalidFiles = [];
89
+				$validFiles = [];
90
+
91
+				foreach ($files as $file) {
92
+					if ($this->$fileTypeValidateFunc($file)) {
93
+						$validFiles[] = $file;
94
+					} else {
95
+						$invalidFiles[] = $file;
96
+					}
97
+				}
98
+
99
+				// If at least one file was valid, count as passed
100
+				if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
101
+					$validFileList = PHP_EOL;
102
+					foreach ($validFiles as $vf) {
103
+						$validFileList .= $vf . PHP_EOL;
104
+					}
105
+					if ($fileTypeValidateFunc == 'noVidation') {
106
+						$checkReturn = [
107
+							EnvironmentCheck::OK,
108
+							sprintf('At least these file(s) accessible: %s', $validFileList)
109
+						];
110
+					} else {
111
+						$checkReturn = [
112
+							EnvironmentCheck::OK,
113
+							sprintf(
114
+								'At least these file(s) passed file type validate function "%s": %s',
115
+								$fileTypeValidateFunc,
116
+								$validFileList
117
+							)
118
+						];
119
+					}
120
+				} else {
121
+					if (count($invalidFiles) == 0) {
122
+						$checkReturn = [EnvironmentCheck::OK, 'All files valideted'];
123
+					} else {
124
+						$invalidFileList = PHP_EOL;
125
+						foreach ($invalidFiles as $vf) {
126
+							$invalidFileList .= $vf . PHP_EOL;
127
+						}
128
+
129
+						if ($fileTypeValidateFunc == 'noVidation') {
130
+							$checkReturn = [
131
+								EnvironmentCheck::ERROR,
132
+								sprintf('File(s) not accessible: %s', $invalidFileList)
133
+							];
134
+						} else {
135
+							$checkReturn = [
136
+								EnvironmentCheck::ERROR,
137
+								sprintf(
138
+									'File(s) not passing the file type validate function "%s": %s',
139
+									$fileTypeValidateFunc,
140
+									$invalidFileList
141
+								)
142
+							];
143
+						}
144
+					}
145
+				}
146
+			} else {
147
+				$checkReturn =  array(
148
+					EnvironmentCheck::ERROR,
149
+					sprintf("Invalid file type validation method name passed: %s ", $fileTypeValidateFunc)
150
+				);
151
+			}
152
+		} else {
153
+			$checkReturn = array(
154
+				EnvironmentCheck::ERROR,
155
+				sprintf("No files accessible at path %s", $this->path)
156
+			);
157
+		}
158
+
159
+		Versioned::set_reading_mode($origStage);
160
+
161
+		return $checkReturn;
162
+	}
163
+
164
+	/**
165
+	 * @param string $file
166
+	 *
167
+	 * @return bool
168
+	 */
169
+	private function jsonValidate($file)
170
+	{
171
+		$json = json_decode(file_get_contents($file));
172
+		if (!$json) {
173
+			return false;
174
+		}
175
+		return true;
176
+	}
177
+
178
+	/**
179
+	 * @param string $file
180
+	 *
181
+	 * @return bool
182
+	 */
183
+	protected function noVidation($file)
184
+	{
185
+		return true;
186
+	}
187
+
188
+	/**
189
+	 * Gets a list of absolute file paths.
190
+	 *
191
+	 * @return array
192
+	 */
193
+	protected function getFiles()
194
+	{
195
+		return glob($this->path);
196
+	}
197 197
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
     public function __construct($path, $fileTypeValidateFunc = 'noVidation', $checkType = null)
68 68
     {
69 69
         $this->path = $path;
70
-        $this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc : 'noVidation';
70
+        $this->fileTypeValidateFunc = ($fileTypeValidateFunc) ? $fileTypeValidateFunc : 'noVidation';
71 71
         $this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
72 72
     }
73 73
 
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
                 if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
101 101
                     $validFileList = PHP_EOL;
102 102
                     foreach ($validFiles as $vf) {
103
-                        $validFileList .= $vf . PHP_EOL;
103
+                        $validFileList .= $vf.PHP_EOL;
104 104
                     }
105 105
                     if ($fileTypeValidateFunc == 'noVidation') {
106 106
                         $checkReturn = [
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
                     } else {
124 124
                         $invalidFileList = PHP_EOL;
125 125
                         foreach ($invalidFiles as $vf) {
126
-                            $invalidFileList .= $vf . PHP_EOL;
126
+                            $invalidFileList .= $vf.PHP_EOL;
127 127
                         }
128 128
 
129 129
                         if ($fileTypeValidateFunc == 'noVidation') {
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
                     }
145 145
                 }
146 146
             } else {
147
-                $checkReturn =  array(
147
+                $checkReturn = array(
148 148
                     EnvironmentCheck::ERROR,
149 149
                     sprintf("Invalid file type validation method name passed: %s ", $fileTypeValidateFunc)
150 150
                 );
Please login to merge, or discard this patch.
src/Checks/FileAgeCheck.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@
 block discarded – undo
92 92
     /**
93 93
      * {@inheritDoc}
94 94
      *
95
-     * @return array
95
+     * @return string[]
96 96
      */
97 97
     public function check()
98 98
     {
Please login to merge, or discard this patch.
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -28,124 +28,124 @@
 block discarded – undo
28 28
  */
29 29
 class FileAgeCheck implements EnvironmentCheck
30 30
 {
31
-    /**
32
-     * @var int
33
-     */
34
-    const CHECK_SINGLE = 1;
31
+	/**
32
+	 * @var int
33
+	 */
34
+	const CHECK_SINGLE = 1;
35 35
 
36
-    /**
37
-     * @var int
38
-     */
39
-    const CHECK_ALL = 2;
36
+	/**
37
+	 * @var int
38
+	 */
39
+	const CHECK_ALL = 2;
40 40
 
41
-    /**
42
-     * Absolute path to a file or folder, compatible with glob().
43
-     *
44
-     * @var string
45
-     */
46
-    protected $path;
41
+	/**
42
+	 * Absolute path to a file or folder, compatible with glob().
43
+	 *
44
+	 * @var string
45
+	 */
46
+	protected $path;
47 47
 
48
-    /**
49
-     * Relative date specification, compatible with strtotime().
50
-     *
51
-     * @var string
52
-     */
53
-    protected $relativeAge;
48
+	/**
49
+	 * Relative date specification, compatible with strtotime().
50
+	 *
51
+	 * @var string
52
+	 */
53
+	protected $relativeAge;
54 54
 
55
-    /**
56
-     * The function to use for checking file age: so filemtime(), filectime(), or fileatime().
57
-     *
58
-     * @var string
59
-     */
60
-    protected $checkFn;
55
+	/**
56
+	 * The function to use for checking file age: so filemtime(), filectime(), or fileatime().
57
+	 *
58
+	 * @var string
59
+	 */
60
+	protected $checkFn;
61 61
 
62
-    /**
63
-     * Constant, check for a single file to match age criteria, or all of them.
64
-     *
65
-     * @var int
66
-     */
67
-    protected $checkType;
62
+	/**
63
+	 * Constant, check for a single file to match age criteria, or all of them.
64
+	 *
65
+	 * @var int
66
+	 */
67
+	protected $checkType;
68 68
 
69
-    /**
70
-     * Type of comparison (either > or <).
71
-     *
72
-     * @var string
73
-     */
74
-    protected $compareOperand;
69
+	/**
70
+	 * Type of comparison (either > or <).
71
+	 *
72
+	 * @var string
73
+	 */
74
+	protected $compareOperand;
75 75
 
76
-    /**
77
-     * @param string $path
78
-     * @param string $relativeAge
79
-     * @param string $compareOperand
80
-     * @param null|int $checkType
81
-     * @param string $checkFn
82
-     */
83
-    public function __construct($path, $relativeAge, $compareOperand = '>', $checkType = null, $checkFn = 'filemtime')
84
-    {
85
-        $this->path = $path;
86
-        $this->relativeAge = $relativeAge;
87
-        $this->checkFn = $checkFn;
88
-        $this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
89
-        $this->compareOperand = $compareOperand;
90
-    }
76
+	/**
77
+	 * @param string $path
78
+	 * @param string $relativeAge
79
+	 * @param string $compareOperand
80
+	 * @param null|int $checkType
81
+	 * @param string $checkFn
82
+	 */
83
+	public function __construct($path, $relativeAge, $compareOperand = '>', $checkType = null, $checkFn = 'filemtime')
84
+	{
85
+		$this->path = $path;
86
+		$this->relativeAge = $relativeAge;
87
+		$this->checkFn = $checkFn;
88
+		$this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
89
+		$this->compareOperand = $compareOperand;
90
+	}
91 91
 
92
-    /**
93
-     * {@inheritDoc}
94
-     *
95
-     * @return array
96
-     */
97
-    public function check()
98
-    {
99
-        $cutoffTime =  strtotime($this->relativeAge, DBDatetime::now()->Format('U'));
100
-        $files = $this->getFiles();
101
-        $invalidFiles = [];
102
-        $validFiles = [];
103
-        $checkFn = $this->checkFn;
104
-        $allValid = true;
105
-        if ($files) {
106
-            foreach ($files as $file) {
107
-                $fileTime = $checkFn($file);
108
-                $valid = ($this->compareOperand == '>') ? ($fileTime >= $cutoffTime) : ($fileTime <= $cutoffTime);
109
-                if ($valid) {
110
-                    $validFiles[] = $file;
111
-                } else {
112
-                    $invalidFiles[] = $file;
113
-                    if ($this->checkType == self::CHECK_ALL) {
114
-                        return [
115
-                            EnvironmentCheck::ERROR,
116
-                            sprintf(
117
-                                'File "%s" doesn\'t match age check (compare %s: %s, actual: %s)',
118
-                                $file,
119
-                                $this->compareOperand,
120
-                                date('c', $cutoffTime),
121
-                                date('c', $fileTime)
122
-                            )
123
-                        ];
124
-                    }
125
-                }
126
-            }
127
-        }
92
+	/**
93
+	 * {@inheritDoc}
94
+	 *
95
+	 * @return array
96
+	 */
97
+	public function check()
98
+	{
99
+		$cutoffTime =  strtotime($this->relativeAge, DBDatetime::now()->Format('U'));
100
+		$files = $this->getFiles();
101
+		$invalidFiles = [];
102
+		$validFiles = [];
103
+		$checkFn = $this->checkFn;
104
+		$allValid = true;
105
+		if ($files) {
106
+			foreach ($files as $file) {
107
+				$fileTime = $checkFn($file);
108
+				$valid = ($this->compareOperand == '>') ? ($fileTime >= $cutoffTime) : ($fileTime <= $cutoffTime);
109
+				if ($valid) {
110
+					$validFiles[] = $file;
111
+				} else {
112
+					$invalidFiles[] = $file;
113
+					if ($this->checkType == self::CHECK_ALL) {
114
+						return [
115
+							EnvironmentCheck::ERROR,
116
+							sprintf(
117
+								'File "%s" doesn\'t match age check (compare %s: %s, actual: %s)',
118
+								$file,
119
+								$this->compareOperand,
120
+								date('c', $cutoffTime),
121
+								date('c', $fileTime)
122
+							)
123
+						];
124
+					}
125
+				}
126
+			}
127
+		}
128 128
 
129
-        // If at least one file was valid, count as passed
130
-        if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
131
-            return [EnvironmentCheck::OK, ''];
132
-        }
133
-        if (count($invalidFiles) == 0) {
134
-            return [EnvironmentCheck::OK, ''];
135
-        }
136
-        return [
137
-            EnvironmentCheck::ERROR,
138
-            sprintf('No files matched criteria (%s %s)', $this->compareOperand, date('c', $cutoffTime))
139
-        ];
140
-    }
129
+		// If at least one file was valid, count as passed
130
+		if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
131
+			return [EnvironmentCheck::OK, ''];
132
+		}
133
+		if (count($invalidFiles) == 0) {
134
+			return [EnvironmentCheck::OK, ''];
135
+		}
136
+		return [
137
+			EnvironmentCheck::ERROR,
138
+			sprintf('No files matched criteria (%s %s)', $this->compareOperand, date('c', $cutoffTime))
139
+		];
140
+	}
141 141
 
142
-    /**
143
-     * Gets a list of absolute file paths.
144
-     *
145
-     * @return array
146
-     */
147
-    protected function getFiles()
148
-    {
149
-        return glob($this->path);
150
-    }
142
+	/**
143
+	 * Gets a list of absolute file paths.
144
+	 *
145
+	 * @return array
146
+	 */
147
+	protected function getFiles()
148
+	{
149
+		return glob($this->path);
150
+	}
151 151
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@
 block discarded – undo
96 96
      */
97 97
     public function check()
98 98
     {
99
-        $cutoffTime =  strtotime($this->relativeAge, DBDatetime::now()->Format('U'));
99
+        $cutoffTime = strtotime($this->relativeAge, DBDatetime::now()->Format('U'));
100 100
         $files = $this->getFiles();
101 101
         $invalidFiles = [];
102 102
         $validFiles = [];
Please login to merge, or discard this patch.
src/Checks/SMTPConnectCheck.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@
 block discarded – undo
53 53
     /**
54 54
      * {@inheritDoc}
55 55
      *
56
-     * @return array
56
+     * @return string[]
57 57
      */
58 58
     public function check()
59 59
     {
Please login to merge, or discard this 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/Controllers/DevCheckController.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -27,7 +27,7 @@
 block discarded – undo
27 27
     private static $permission = 'ADMIN';
28 28
 
29 29
     /**
30
-     * @param HTTPRequest $request
30
+     * @param \SilverStripe\Control\HTTPRequest $request
31 31
      *
32 32
      * @return EnvironmentChecker
33 33
      *
Please login to merge, or discard this 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/EnvironmentCheckSuite.php 4 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
     /**
107 107
      * Run this test suite and return the result code of the worst result.
108 108
      *
109
-     * @return int
109
+     * @return EnvironmentCheckSuiteResult
110 110
      */
111 111
     public function run()
112 112
     {
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
     /**
196 196
      * Register a check against the named check suite.
197 197
      *
198
-     * @param string|array $names
198
+     * @param string $names
199 199
      * @param EnvironmentCheck $check
200 200
      * @param string|array
201 201
      */
Please login to merge, or discard this patch.
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -9,9 +9,6 @@
 block discarded – undo
9 9
 use SilverStripe\Core\Injector\Injectable;
10 10
 use SilverStripe\Core\Injector\Injector;
11 11
 use SilverStripe\EnvironmentCheck\EnvironmentCheck;
12
-use SilverStripe\ORM\ArrayList;
13
-use SilverStripe\View\ArrayData;
14
-use SilverStripe\View\ViewableData;
15 12
 
16 13
 /**
17 14
  * Represents a suite of environment checks.
Please login to merge, or discard this 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.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@
 block discarded – undo
150 150
             } elseif ($checkClass instanceof EnvironmentCheck) {
151 151
                 $output[] = [$checkClass, $checkTitle];
152 152
             } else {
153
-                throw new InvalidArgumentException("Bad EnvironmentCheck: " . var_export($check, true));
153
+                throw new InvalidArgumentException("Bad EnvironmentCheck: ".var_export($check, true));
154 154
             }
155 155
         }
156 156
         return $output;
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/EnvironmentChecker.php 2 patches
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.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -280,7 +280,7 @@
 block discarded – undo
280 280
     public static function set_to_email_address($to)
281 281
     {
282 282
         Deprecation::notice('2.0', 'Use config API instead');
283
-        Config::modify()->set(__CLASS__, 'to_email_address',  $to);
283
+        Config::modify()->set(__CLASS__, 'to_email_address', $to);
284 284
     }
285 285
 
286 286
     /**
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 2 patches
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.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@
 block discarded – undo
56 56
         if (!empty($brokenCores)) {
57 57
             return [
58 58
                 EnvironmentCheck::ERROR,
59
-                'The following indexes are unavailable: ' . implode($brokenCores, ', ')
59
+                'The following indexes are unavailable: '.implode($brokenCores, ', ')
60 60
             ];
61 61
         }
62 62
 
Please login to merge, or discard this patch.