Skip to content

Commit 8bdbd56

Browse files
committed
PHP 8.1 | Config: fix passing null to non-nullable notice
As per issue 3760, if the `stty size` command errors out, `shell_exec()` will return `null`. Per the [documentation](https://www.php.net/manual/en/function.shell-exec.php#refsect1-function.shell-exec-returnvalues), the `shell_exec()` command can also return `false`, which would also be an unusable value (`preg_match()` will not match, so `'auto'` would be cast to int, resulting in `0` being set as the value). If the output of `shell_exec()` would be `null`, PHP as of PHP 8.1 will throw a "passing null to non-nullable" notice. Additionally, if the output from `shell_exec()` would be `false`, the original input would be an invalid non-numeric value or the original input would be `auto`, but the `shell_exec()` command is disabled, the code as-it-was, would set the `reportWidth` to `0`, which is not that helpful. See: https://3v4l.org/GE7sK I've now changed the logic to: * If the received value is `auto`, check if a valid CLI width can be determined and only then use that value. * In all other cases, including when the value is set directly on the object, the value will be validated and if not valid, a default value of width `80` will be used, which is in line with the default width as stated in [the documentation](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Configuration-Options#setting-the-default-report-width). Fixes 3760
1 parent c85ac6a commit 8bdbd56

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

src/Config.php

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,13 @@ class Config
8989
*/
9090
const STABILITY = 'stable';
9191

92+
/**
93+
* Default report width when no report width is provided and 'auto' does not yield a valid width.
94+
*
95+
* @var int
96+
*/
97+
const DEFAULT_REPORT_WIDTH = 80;
98+
9299
/**
93100
* An array of settings that PHPCS and PHPCBF accept.
94101
*
@@ -223,13 +230,20 @@ public function __set($name, $value)
223230
switch ($name) {
224231
case 'reportWidth' :
225232
// Support auto terminal width.
226-
if ($value === 'auto'
227-
&& function_exists('shell_exec') === true
228-
&& preg_match('|\d+ (\d+)|', shell_exec('stty size 2>&1'), $matches) === 1
229-
) {
230-
$value = (int) $matches[1];
231-
} else {
233+
if ($value === 'auto' && function_exists('shell_exec') === true) {
234+
$dimensions = shell_exec('stty size 2>&1');
235+
if (is_string($dimensions) === true && preg_match('|\d+ (\d+)|', $dimensions, $matches) === 1) {
236+
$value = (int) $matches[1];
237+
break;
238+
}
239+
}
240+
241+
if (is_int($value) === true) {
242+
$value = abs($value);
243+
} else if (is_string($value) === true && preg_match('`^\d+$`', $value) === 1) {
232244
$value = (int) $value;
245+
} else {
246+
$value = self::DEFAULT_REPORT_WIDTH;
233247
}
234248
break;
235249
case 'standards' :

0 commit comments

Comments
 (0)