PHPStan: Enable more checks (#14318)

* PHPStan: Enable more checks

* Fixes

* Fixes

* Deprecation fixes
This commit is contained in:
Jellyfrog 2022-09-09 14:08:06 +02:00 committed by GitHub
parent 6cc9694780
commit 152497a098
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 92 additions and 110 deletions

View File

@ -76,8 +76,8 @@ jobs:
-
name: Run PHPStan (Deprecated functions)
run: ./vendor/bin/phpstan analyze --no-interaction --no-progress --error-format=github --memory-limit=4G --configuration=phpstan-deprecated.neon
run: ./vendor/bin/phpstan analyze --no-interaction --no-progress --memory-limit=4G --configuration=phpstan-deprecated.neon
-
name: Run PHPStan
run: ./vendor/bin/phpstan analyze --no-interaction --no-progress --error-format=github --memory-limit=4G
run: ./vendor/bin/phpstan analyze --no-interaction --no-progress --memory-limit=4G

View File

@ -39,7 +39,7 @@ class Elasticsearch extends Transport
{
$es_host = '127.0.0.1';
$es_port = 9200;
$index = strftime('librenms-%Y.%m.%d');
$index = date("\l\i\b\\r\\e\\n\m\s\-Y.m.d");
$type = 'alert';
$severity = $obj['severity'];
@ -61,7 +61,7 @@ class Elasticsearch extends Transport
}
if (! empty($opts['es_index'])) {
$index = strftime($opts['es_index']);
$index = date($opts['es_index']);
}
$host = $es_host . ':' . $es_port . '/' . $index . '/' . $type;
@ -222,7 +222,7 @@ class Elasticsearch extends Transport
[
'title' => 'Index Pattern',
'name' => 'es-pattern',
'descr' => 'Elasticsearch Index Pattern',
'descr' => 'Elasticsearch Index Pattern | Default: \l\i\b\\r\\e\\n\m\s\-Y.m.d | Format: https://www.php.net/manual/en/function.date.php',
'type' => 'text',
],
[

View File

@ -16,7 +16,7 @@ class Linenotify extends Transport
{
$opts['line-notify-access-token'] = $this->config['line-notify-access-token'];
return $this->contactLineNotify($obj, $opts);
return $this->contactLinenotify($obj, $opts);
}
private function contactLinenotify($obj, $opts)

View File

@ -27,7 +27,7 @@ class Twilio extends Transport
$twilio_opts['sender'] = $this->config['twilio-sender'];
$twilio_opts['to'] = $this->config['twilio-to'];
return $this->contacttwilio($obj, $twilio_opts);
return $this->contactTwilio($obj, $twilio_opts);
}
public static function contactTwilio($obj, $opts)

View File

@ -124,10 +124,10 @@ class SSOAuthorizer extends MysqlAuthorizer
foreach ($proxies as $value) {
$proxy = IP::parse($value);
if ($proxies == '8.8.8.0/25') {
dd($source->innetwork((string) $proxy));
dd($source->inNetwork((string) $proxy));
}
if ($source->innetwork((string) $proxy)) {
if ($source->inNetwork((string) $proxy)) {
// Proxy matches trusted subnet
return true;
}

View File

@ -460,7 +460,7 @@ class Rrd extends BaseDatastore
public function getRrdFiles($device)
{
if ($this->rrdcached) {
$filename = sprintf('/%s', self::safename($device['hostname']));
$filename = sprintf('/%s', self::safeName($device['hostname']));
$rrd_files = $this->command('list', $filename, '');
// Command output is an array, create new array with each filename as a item in array.
$rrd_files_array = explode("\n", trim($rrd_files[0]));

View File

@ -28,7 +28,6 @@ namespace LibreNMS\Device;
use Illuminate\Support\Str;
use LibreNMS\Interfaces\Discovery\DiscoveryItem;
use LibreNMS\Interfaces\Discovery\DiscoveryModule;
use LibreNMS\Interfaces\Discovery\ProcessorDiscovery;
use LibreNMS\Interfaces\Polling\PollerModule;
use LibreNMS\Interfaces\Polling\ProcessorPolling;
use LibreNMS\Model;
@ -142,7 +141,7 @@ class Processor extends Model implements DiscoveryModule, PollerModule, Discover
$processors = self::processYaml($os);
// if no processors found, check OS discovery (which will fall back to HR and UCD if not implemented
if (empty($processors) && $os instanceof ProcessorDiscovery) {
if (empty($processors)) {
$processors = $os->discoverProcessors();
}

View File

@ -144,7 +144,7 @@ class Isis implements Module
'isisISAdjLastUpTime' => $this->parseAdjacencyTime($adjacency_data),
'isisISAdjAreaAddress' => str_replace(' ', '.', trim($adjacency_data['isisISAdjAreaAddress'] ?? '')),
'isisISAdjIPAddrType' => $adjacency_data['isisISAdjIPAddrType'] ?? '',
'isisISAdjIPAddrAddress' => (string) IP::fromHexstring($adjacency_data['isisISAdjIPAddrAddress'] ?? null, true),
'isisISAdjIPAddrAddress' => (string) IP::fromHexString($adjacency_data['isisISAdjIPAddrAddress'] ?? null, true),
]);
}

View File

@ -30,7 +30,6 @@ use App\Models\Mempool;
use App\Observers\MempoolObserver;
use Illuminate\Support\Collection;
use LibreNMS\DB\SyncsModels;
use LibreNMS\Interfaces\Discovery\MempoolsDiscovery;
use LibreNMS\Interfaces\Module;
use LibreNMS\Interfaces\Polling\MempoolsPolling;
use LibreNMS\OS;
@ -52,25 +51,23 @@ class Mempools implements Module
public function discover(OS $os): void
{
if ($os instanceof MempoolsDiscovery) {
$mempools = $os->discoverMempools()->filter(function (Mempool $mempool) {
if ($mempool->isValid()) {
return true;
}
Log::debug("Rejecting Mempool $mempool->mempool_index $mempool->mempool_descr: Invalid total value");
$mempools = $os->discoverMempools()->filter(function (Mempool $mempool) {
if ($mempool->isValid()) {
return true;
}
Log::debug("Rejecting Mempool $mempool->mempool_index $mempool->mempool_descr: Invalid total value");
return false;
});
$this->calculateAvailable($mempools);
return false;
});
$this->calculateAvailable($mempools);
MempoolObserver::observe('\App\Models\Mempool');
$this->syncModels($os->getDevice(), 'mempools', $mempools);
MempoolObserver::observe('\App\Models\Mempool');
$this->syncModels($os->getDevice(), 'mempools', $mempools);
echo PHP_EOL;
$mempools->each(function ($mempool) {
$this->printMempool($mempool);
});
}
echo PHP_EOL;
$mempools->each(function ($mempool) {
$this->printMempool($mempool);
});
}
public function poll(OS $os): void

View File

@ -29,11 +29,7 @@ use App\Models\Device;
use App\Models\PortStp;
use App\Observers\ModuleModelObserver;
use LibreNMS\DB\SyncsModels;
use LibreNMS\Interfaces\Discovery\StpInstanceDiscovery;
use LibreNMS\Interfaces\Discovery\StpPortDiscovery;
use LibreNMS\Interfaces\Module;
use LibreNMS\Interfaces\Polling\StpInstancePolling;
use LibreNMS\Interfaces\Polling\StpPortPolling;
use LibreNMS\OS;
class Stp implements Module
@ -52,40 +48,33 @@ class Stp implements Module
{
$device = $os->getDevice();
if ($os instanceof StpInstanceDiscovery) {
echo 'Instances: ';
$instances = $os->discoverStpInstances();
ModuleModelObserver::observe(\App\Models\Stp::class);
$this->syncModels($device, 'stpInstances', $instances);
echo 'Instances: ';
$instances = $os->discoverStpInstances();
ModuleModelObserver::observe(\App\Models\Stp::class);
$this->syncModels($device, 'stpInstances', $instances);
if ($os instanceof StpPortDiscovery) {
echo "\nPorts: ";
$ports = $os->discoverStpPorts($instances);
ModuleModelObserver::observe(PortStp::class);
$this->syncModels($device, 'stpPorts', $ports);
}
echo PHP_EOL;
}
echo "\nPorts: ";
$ports = $os->discoverStpPorts($instances);
ModuleModelObserver::observe(PortStp::class);
$this->syncModels($device, 'stpPorts', $ports);
echo PHP_EOL;
}
public function poll(OS $os): void
{
$device = $os->getDevice();
if ($os instanceof StpInstancePolling) {
echo 'Instances: ';
$instances = $device->stpInstances;
$instances = $os->pollStpInstances($instances);
ModuleModelObserver::observe(\App\Models\Stp::class);
$this->syncModels($device, 'stpInstances', $instances);
}
echo 'Instances: ';
$instances = $device->stpInstances;
$instances = $os->pollStpInstances($instances);
ModuleModelObserver::observe(\App\Models\Stp::class);
$this->syncModels($device, 'stpInstances', $instances);
if ($os instanceof StpPortPolling) {
echo "\nPorts: ";
$ports = $device->stpPorts;
ModuleModelObserver::observe(PortStp::class);
$this->syncModels($device, 'stpPorts', $ports);
}
echo "\nPorts: ";
$ports = $device->stpPorts;
ModuleModelObserver::observe(PortStp::class);
$this->syncModels($device, 'stpPorts', $ports);
}
public function cleanup(Device $device): void

View File

@ -92,7 +92,7 @@ class Ciscowlc extends Cisco implements
d_echo($ap->toArray());
// if there is a numeric channel, assume the rest of the data is valid, I guess
if (! is_numeric($ap->channel)) {
if (! is_numeric($channel)) {
continue;
}

View File

@ -37,7 +37,7 @@ class Ifotec extends OS implements OSDiscovery
if (Str::startsWith($device->sysObjectID, '.1.3.6.1.4.1.21362.100.')) {
$ifoSysProductIndex = snmp_get($this->getDeviceArray(), 'ifoSysProductIndex.0', '-Oqv', 'IFOTEC-SMI');
if ($ifoSysProductIndex !== null) {
if ($ifoSysProductIndex !== false) {
$oids = [
'ifoSysSerialNumber.' . $ifoSysProductIndex,
'ifoSysFirmware.' . $ifoSysProductIndex,

View File

@ -107,7 +107,7 @@ class Iosxe extends Ciscowlc implements
'isisISAdjAreaAddress' => implode(',', array_map([$this, 'formatIsIsId'], $adjacency_data['CISCO-IETF-ISIS-MIB::ciiISAdjAreaAddress'] ?? [])),
'isisISAdjIPAddrType' => implode(',', $adjacency_data['CISCO-IETF-ISIS-MIB::ciiISAdjIPAddrType'] ?? []),
'isisISAdjIPAddrAddress' => implode(',', array_map(function ($ip) {
return (string) IP::fromHexstring($ip, true);
return (string) IP::fromHexString($ip, true);
}, $adjacency_data['CISCO-IETF-ISIS-MIB::ciiISAdjIPAddrAddress'] ?? [])),
]));
}

View File

@ -431,7 +431,7 @@ class Cisco extends OS implements
// Lets process each SLA
$unixtime = intval(($data[$sla_nr]['rttMonLatestRttOperTime'] / 100 + $time_offset));
$time = strftime('%Y-%m-%d %H:%M:%S', $unixtime);
$time = date('Y-m-d H:i:s', $unixtime);
// Save data
$sla->rtt = $data[$sla_nr]['rttMonLatestRttOperCompletionTime'];

View File

@ -40,7 +40,7 @@ trait FrogfootResources
return [
Processor::discover(
$this->getName(),
$this->getDeviceID(),
$this->getDeviceId(),
'1.3.6.1.4.1.10002.1.1.1.4.2.1.3.2',
0
),

View File

@ -260,6 +260,7 @@ class Proc
*/
public function isRunning()
{
/* @phpstan-ignore-next-line */
if (! is_resource($this->_process)) {
return false;
}

View File

@ -75,7 +75,6 @@ class Clean
*/
public static function html($value, $purifier_config = [])
{
/** @var HTMLPurifier $purifier */
static $purifier;
// If $purifier_config is non-empty then we don't want

View File

@ -74,7 +74,7 @@ class AboutController extends Controller
'version_local' => $version->local(),
'version_database' => $version->databaseServer(),
'version_php' => phpversion(),
'version_laravel' => App::VERSION(),
'version_laravel' => App::version(),
'version_python' => $version->python(),
'version_webserver' => $request->server('SERVER_SOFTWARE'),
'version_rrdtool' => Rrd::version(),

View File

@ -59,7 +59,7 @@ class VmInfoController implements DeviceTab
private static function getVms(Device $device)
{
return $device->vmInfo()
return $device->vminfo()
->select('vmwVmDisplayName', 'vmwVmState', 'vmwVmGuestOS', 'vmwVmMemSize', 'vmwVmCpus')
->with('parentDevice')
->orderBy('vmwVmDisplayName')

View File

@ -65,7 +65,7 @@ class DeviceGroup extends BaseModel
public function updateDevices()
{
if ($this->type == 'dynamic') {
$this->devices()->sync(QueryBuilderFluentParser::fromJSON($this->rules)->toQuery()
$this->devices()->sync(QueryBuilderFluentParser::fromJson($this->rules)->toQuery()
->distinct()->pluck('devices.device_id'));
}
}

View File

@ -91,7 +91,7 @@ class ServiceTemplate extends BaseModel
public function updateDevices()
{
if ($this->type == 'dynamic') {
$this->devices()->sync(QueryBuilderFluentParser::fromJSON($this->rules)->toQuery()
$this->devices()->sync(QueryBuilderFluentParser::fromJson($this->rules)->toQuery()
->distinct()->pluck('devices.device_id'));
}
}

View File

@ -99,9 +99,6 @@ class UserPref extends BaseModel
{
/** @var array */
$keys = $this->getKeyName();
if (! is_array($keys)) {
return parent::setKeysForSaveQuery($query);
}
foreach ($keys as $keyName) {
$query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));

View File

@ -46,6 +46,7 @@ class ErrorReportingProvider extends \Facade\Ignition\IgnitionServiceProvider
public function boot(): void
{
/* @phpstan-ignore-next-line */
if (! method_exists(\Facade\FlareClient\Flare::class, 'filterReportsUsing')) {
Log::debug("Flare client too old, disabling Ignition to avoid bug.\n");

View File

@ -353,8 +353,8 @@ function getHistoricTransferGraphData($bill_id)
$allowed_val = null;
foreach (dbFetchRows('SELECT * FROM `bill_history` WHERE `bill_id` = ? ORDER BY `bill_datefrom` DESC LIMIT 12', [$bill_id]) as $data) {
$datefrom = strftime('%Y-%m-%d', strtotime($data['bill_datefrom']));
$dateto = strftime('%Y-%m-%d', strtotime($data['bill_dateto']));
$datefrom = date('Y-m-d', strtotime($data['bill_datefrom']));
$dateto = date('Y-m-d', strtotime($data['bill_dateto']));
$datelabel = $datefrom . ' - ' . $dateto;
array_push($ticklabels, $datelabel);
@ -421,7 +421,7 @@ function getBillingBandwidthGraphData($bill_id, $bill_hist_id, $from, $to, $imgt
$average = 0;
if ($imgtype == 'day') {
foreach (dbFetch('SELECT DISTINCT UNIX_TIMESTAMP(timestamp) as timestamp, SUM(delta) as traf_total, SUM(in_delta) as traf_in, SUM(out_delta) as traf_out FROM bill_data WHERE `bill_id` = ? AND `timestamp` >= FROM_UNIXTIME(?) AND `timestamp` <= FROM_UNIXTIME(?) GROUP BY DATE(timestamp) ORDER BY timestamp ASC', [$bill_id, $from, $to]) as $data) {
array_push($ticklabels, strftime('%Y-%m-%d', $data['timestamp']));
array_push($ticklabels, date('Y-m-d', $data['timestamp']));
array_push($in_data, isset($data['traf_in']) ? $data['traf_in'] : 0);
array_push($out_data, isset($data['traf_out']) ? $data['traf_out'] : 0);
array_push($tot_data, isset($data['traf_total']) ? $data['traf_total'] : 0);
@ -431,7 +431,7 @@ function getBillingBandwidthGraphData($bill_id, $bill_hist_id, $from, $to, $imgt
$ave_count = count($tot_data);
// Add empty items for the days not yet passed
$days = (strftime('%e', date($to - $from)) - $ave_count - 1);
$days = (date('j', date($to - $from)) - $ave_count - 1);
for ($x = 0; $x < $days; $x++) {
array_push($ticklabels, '');
array_push($in_data, 0);

View File

@ -38,18 +38,7 @@ function read_var($name, &$array, $default = null)
{
if (isset($array[$name])) {
if (is_array($array[$name])) {
if (get_magic_quotes_gpc()) {
$ret = [];
foreach ($array[$name] as $k => $v) {
$ret[stripslashes($k)] = stripslashes($v);
}
return $ret;
} else {
return $array[$name];
}
} elseif (is_string($array[$name]) && get_magic_quotes_gpc()) {
return stripslashes($array[$name]);
return $array[$name];
} else {
return $array[$name];
}

View File

@ -17,9 +17,9 @@ for ($i = 0; $i < count($graph_data['ticklabels']); $i++) {
if (date('m', $start) == date('m', $end) && date('d', $start == 1)) {
// Calendar months, omit the date and the end!
$graph_data['ticklabels'][$i] = strftime('%b %Y', $start);
$graph_data['ticklabels'][$i] = date('M Y', $start);
} else {
$graph_data['ticklabels'][$i] = strftime('%e %b %Y', $start) . "\n" . strftime('%e %b %Y', $end);
$graph_data['ticklabels'][$i] = date('j M Y', $start) . "\n" . date('j M Y', $end);
}
}
}

View File

@ -21,7 +21,7 @@ for ($i = 0; $i < count($graph_data['ticklabels']); $i++) {
$date = strtotime($graph_data['ticklabels'][$i]);
if ($vars['imgtype'] === 'day') {
$graph_data['ticklabels'][$i] = strftime("%e\n%b", $date);
$graph_data['ticklabels'][$i] = date("j\nM", $date);
}
}
}

View File

@ -104,7 +104,7 @@ foreach (dbFetchRows('SELECT * FROM `bill_history` WHERE `bill_id` = ? ORDER BY
echo '
<tr>
<td></td>
<td><span style="font-weight: bold;" class="interface">' . strftime('%Y-%m-%d', strtotime($datefrom)) . ' to ' . strftime('%Y-%m-%d', strtotime($dateto)) . "</span></td>
<td><span style="font-weight: bold;" class="interface">' . date('Y-m-d', strtotime($datefrom)) . ' to ' . date('Y-m-d', strtotime($dateto)) . "</span></td>
<td>$type</td>
<td>$allowed</td>
<td>$in</td>

View File

@ -143,7 +143,7 @@ foreach (dbFetchRows($sql, $param) as $bill) {
$overuse_formatted = (($overuse <= 0) ? '-' : "<span style='color: #${background['left']}; font-weight: bold;'>$overuse_formatted</span>");
$bill_name = "<a href='$url'><span style='font-weight: bold;' class='interface'>${bill['bill_name']}</span></a><br />" .
strftime('%F', strtotime($datefrom)) . ' to ' . strftime('%F', strtotime($dateto));
date('Y-m-d', strtotime($datefrom)) . ' to ' . date('Y-m-d', strtotime($dateto));
$bar = print_percentage_bar(250, 20, $percent, null, 'ffffff', $background['left'], $percent . '%', 'ffffff', $background['right']);
$actions = '';

View File

@ -87,7 +87,7 @@ function parse_rss($feed)
'title'=>$item['title'],
'body'=>$item['description'],
'checksum'=>hash('sha512', $item['title'] . $item['description']),
'datetime'=>strftime('%F', strtotime($item['pubDate']) ?: time()),
'datetime'=>date('Y-m-d', strtotime($item['pubDate']) ?: time()),
];
}
@ -111,7 +111,7 @@ function parse_atom($feed)
'title'=>$item['title'],
'body'=>$item['content'],
'checksum'=>hash('sha512', $item['title'] . $item['content']),
'datetime'=>strftime('%F', strtotime($item['updated']) ?: time()),
'datetime'=>date('Y-m-d', strtotime($item['updated']) ?: time()),
];
}
@ -136,7 +136,7 @@ function new_notification($title, $message, $severity = 0, $source = 'adhoc', $d
'severity' => $severity,
'source' => $source,
'checksum' => hash('sha512', $title . $message),
'datetime' => strftime('%F', is_null($date) ? time() : strtotime($date)),
'datetime' => date('Y-m-d', is_null($date) ? time() : strtotime($date)),
];
if (dbFetchCell('SELECT 1 FROM `notifications` WHERE `checksum` = ?', [$notif['checksum']]) != 1) {

View File

@ -415,11 +415,6 @@ parameters:
count: 1
path: LibreNMS/Alert/Transport/Linenotify.php
-
message: "#^Method LibreNMS\\\\Alert\\\\Transport\\\\Linenotify\\:\\:contactLinenotify\\(\\) is unused\\.$#"
count: 1
path: LibreNMS/Alert/Transport/Linenotify.php
-
message: "#^Method LibreNMS\\\\Alert\\\\Transport\\\\Mail\\:\\:contactMail\\(\\) has no return type specified\\.$#"
count: 1

View File

@ -3,26 +3,25 @@ includes:
- phpstan-baseline-deprecated.neon
parameters:
phpVersion: 70300
customRulesetUsed: true
reportUnmatchedIgnoredErrors: false
resultCachePath: %tmpDir%/resultCache-deprecated.php
paths:
- LibreNMS
- app
- bootstrap
- cache
- html
- storage
- app
- config
- database
- doc
- html
- includes
- LibreNMS
- licenses
- misc
- resources
- routes
- sql-schema
- storage
- tests

View File

@ -24,8 +24,19 @@ parameters:
checkMissingIterableValueType: false
treatPhpDocTypesAsCertain: false
checkFunctionNameCase: true
checkInternalClassCaseSensitivity: true
checkModelProperties: true
checkAlwaysTrueCheckTypeFunctionCall: true
checkAlwaysTrueInstanceof: true
checkAlwaysTrueStrictComparison: true
ignoreErrors:
- '#Unsafe usage of new static#'
parallel:
processTimeout: 300.0

View File

@ -28,7 +28,7 @@ if (php_sapi_name() === 'cli') {
require realpath(__DIR__ . '/..') . '/includes/init.php';
$return = \Artisan::call('smokeping:generate --targets --no-header --no-dns --single-process --compat');
echo \Artisan::Output();
echo \Artisan::output();
exit($return);
}

View File

@ -139,7 +139,7 @@ class MibTest extends TestCase
if ($file->isDir()) {
continue;
}
$mib_path = str_replace(Config::get('mib_dir') . '/', '', $file->getPathName());
$mib_path = str_replace(Config::get('mib_dir') . '/', '', $file->getPathname());
$file_list[$mib_path] = [
str_replace(Config::get('install_dir'), '.', $file->getPath()),
$file->getFilename(),

View File

@ -342,7 +342,7 @@ class SmokepingCliTest extends DBTestCase
// Disable DNS lookups
\Artisan::call('smokeping:generate --targets --no-header --no-dns --single-process --compat');
$new = \Artisan::Output();
$new = \Artisan::output();
$old = $this->legacyAlgo($data);
$this->assertEquals($this->canonicalise($new), $this->canonicalise($old));

View File

@ -4,3 +4,8 @@ parameters:
- "#^Method LibreNMS\\\\Authentication\\\\LdapAuthorizer\\:\\:getLdapConnection\\(\\) has invalid return type LDAP\\\\Connection\\.$#"
- "#^Parameter \\#1 \\$ldap of function ldap_.* expects (array\\|)?resource, LDAP\\\\Connection given\\.$#"
-
message: "#^Call to an undefined static method Illuminate\\\\Support\\\\Facades\\\\Redis\\:\\:ping()\\.$#"
count: 1
path: ../../LibreNMS/Validations/Poller/CheckRedis.php