Skip to content

Commit

Permalink
PHP 8.1 | Config: fix passing null to non-nullable notice
Browse files Browse the repository at this point in the history
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
  • Loading branch information
jrfnl committed May 5, 2023
1 parent c85ac6a commit 8bdbd56
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ class Config
*/
const STABILITY = 'stable';

/**
* Default report width when no report width is provided and 'auto' does not yield a valid width.
*
* @var int
*/
const DEFAULT_REPORT_WIDTH = 80;

/**
* An array of settings that PHPCS and PHPCBF accept.
*
Expand Down Expand Up @@ -223,13 +230,20 @@ public function __set($name, $value)
switch ($name) {
case 'reportWidth' :
// Support auto terminal width.
if ($value === 'auto'
&& function_exists('shell_exec') === true
&& preg_match('|\d+ (\d+)|', shell_exec('stty size 2>&1'), $matches) === 1
) {
$value = (int) $matches[1];
} else {
if ($value === 'auto' && function_exists('shell_exec') === true) {
$dimensions = shell_exec('stty size 2>&1');
if (is_string($dimensions) === true && preg_match('|\d+ (\d+)|', $dimensions, $matches) === 1) {
$value = (int) $matches[1];
break;
}
}

if (is_int($value) === true) {
$value = abs($value);
} else if (is_string($value) === true && preg_match('`^\d+$`', $value) === 1) {
$value = (int) $value;
} else {
$value = self::DEFAULT_REPORT_WIDTH;
}
break;
case 'standards' :
Expand Down

0 comments on commit 8bdbd56

Please sign in to comment.