Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Github Actions: Add Phpstan #186

Merged
merged 11 commits into from
Sep 1, 2023
15 changes: 12 additions & 3 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,21 @@ jobs:
tools: phpcs

- name: Setup dependencies
run: composer require -n --no-progress overtrue/phplint
run: |
composer require -n --no-progress overtrue/phplint
git clone --depth 1 https://github.com/Icinga/icingaweb2.git vendor/icingaweb2
git clone --depth 1 https://github.com/Icinga/icingaweb2-module-director.git vendor/director
git clone --depth 1 -b snapshot/nightly https://github.com/Icinga/icinga-php-library.git vendor/icinga-php-library
git clone --depth 1 -b snapshot/nightly https://github.com/Icinga/icinga-php-thirdparty.git vendor/icinga-php-thirdparty

- name: PHP Lint
if: success() || matrix.allow_failure
if: ${{ ! cancelled() }}
run: ./vendor/bin/phplint -n --exclude={^vendor/.*} -- .

- name: PHP CodeSniffer
if: success() || matrix.allow_failure
if: ${{ ! cancelled() }}
run: phpcs

- name: PHPStan
if: ${{ ! cancelled() }}
uses: php-actions/phpstan@v3
35 changes: 16 additions & 19 deletions application/clicommands/CheckCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,18 @@

namespace Icinga\Module\X509\Clicommands;

use DateInterval;
use DateTime;
use DateTimeInterface;
use Icinga\Application\Logger;
use Icinga\Module\X509\Command;
use Icinga\Module\X509\Model\X509Certificate;
use Icinga\Module\X509\Model\X509CertificateChain;
use Icinga\Module\X509\Model\X509Target;
use ipl\Sql\Expression;
use ipl\Stdlib\Filter;

class CheckCommand extends Command
{
public const UNIT_PERCENT = 'percent';
public const UNIT_INTERVAL = 'interval';

/**
* Check a host's certificate
*
Expand Down Expand Up @@ -127,8 +125,8 @@ public function hostAction()
}

$allowSelfSigned = (bool) $this->params->get('allow-self-signed', false);
list($warningThreshold, $warningUnit) = $this->splitThreshold($this->params->get('warning', '25%'));
list($criticalThreshold, $criticalUnit) = $this->splitThreshold($this->params->get('critical', '10%'));
$warningThreshold = $this->splitThreshold($this->params->get('warning', '25%'));
$criticalThreshold = $this->splitThreshold($this->params->get('critical', '10%'));

$output = [];
$perfData = [];
Expand All @@ -144,8 +142,8 @@ public function hostAction()
$now = new DateTime();
$validFrom = DateTime::createFromFormat('U.u', sprintf('%F', $target->valid_from / 1000.0));
$validTo = DateTime::createFromFormat('U.u', sprintf('%F', $target->valid_to / 1000.0));
$criticalAfter = $this->thresholdToDateTime($validFrom, $validTo, $criticalThreshold, $criticalUnit);
$warningAfter = $this->thresholdToDateTime($validFrom, $validTo, $warningThreshold, $warningUnit);
$criticalAfter = $this->thresholdToDateTime($validFrom, $validTo, $criticalThreshold);
$warningAfter = $this->thresholdToDateTime($validFrom, $validTo, $warningThreshold);

if ($now > $criticalAfter) {
$state = 2;
Expand Down Expand Up @@ -203,11 +201,11 @@ public function hostAction()
/**
* Parse the given threshold definition
*
* @param string $threshold
* @param string $threshold
*
* @return array
* @return int|DateInterval
*/
protected function splitThreshold($threshold)
protected function splitThreshold(string $threshold)
{
$match = preg_match('/(\d+)([%\w]{1})/', $threshold, $matches);
if (! $match) {
Expand All @@ -217,7 +215,7 @@ protected function splitThreshold($threshold)

switch ($matches[2]) {
case '%':
return [(int) $matches[1], self::UNIT_PERCENT];
return (int) $matches[1];
case 'y':
case 'Y':
$intervalSpec = 'P' . $matches[1] . 'Y';
Expand Down Expand Up @@ -245,27 +243,26 @@ protected function splitThreshold($threshold)
exit(3);
}

return [new \DateInterval($intervalSpec), self::UNIT_INTERVAL];
return new DateInterval($intervalSpec);
}

/**
* Convert the given threshold information to a DateTime object
*
* @param DateTime $from
* @param DateTime $to
* @param int|\DateInterval $thresholdValue
* @param string $thresholdUnit
* @param int|DateInterval $thresholdValue
*
* @return DateTime
* @return DateTimeInterface
*/
protected function thresholdToDateTime(DateTime $from, DateTime $to, $thresholdValue, $thresholdUnit)
protected function thresholdToDateTime(DateTime $from, DateTime $to, $thresholdValue): DateTimeInterface
{
$to = clone $to;
if ($thresholdUnit === self::UNIT_INTERVAL) {
if ($thresholdValue instanceof DateInterval) {
return $to->sub($thresholdValue);
}

$coveredDays = (int) round($from->diff($to)->days * ($thresholdValue / 100));
return $to->sub(new \DateInterval('P' . $coveredDays . 'D'));
return $to->sub(new DateInterval('P' . $coveredDays . 'D'));
}
}
1 change: 1 addition & 0 deletions application/controllers/CertificateController.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public function indexAction()
return;
}

/** @var ?X509Certificate $cert */
$cert = X509Certificate::on($conn)
->filter(Filter::equal('id', $certId))
->first();
Expand Down
1 change: 1 addition & 0 deletions application/controllers/ChainController.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public function indexAction()
return;
}

/** @var ?X509CertificateChain $chain */
$chain = X509CertificateChain::on($conn)
->with(['target'])
->filter(Filter::equal('id', $id))
Expand Down
7 changes: 4 additions & 3 deletions application/controllers/JobsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use ipl\Scheduler\Contract\Frequency;
use ipl\Scheduler\Cron;
use ipl\Web\Compat\CompatController;
use stdClass;

class JobsController extends CompatController
{
Expand Down Expand Up @@ -89,12 +90,12 @@ protected function prepareForm(bool $isNew = false)
if (! $isNew) {
$name = $this->params->getRequired('name');
$query = $repo->select()->where('name', $name);

if (! $query->hasResult()) {
/** @var false|stdClass $data */
$data = $query->fetchRow();
if ($data === false) {
$this->httpNotFound($this->translate('Job not found'));
}

$data = $query->fetchRow();
if (! isset($data->frequencyType) && ! empty($data->schedule)) {
$frequency = new Cron($data->schedule);
} elseif (! empty($data->schedule)) {
Expand Down
7 changes: 4 additions & 3 deletions library/X509/CertificateUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Icinga\Module\X509\Model\X509CertificateSubjectAltName;
use Icinga\Module\X509\Model\X509Dn;
use Icinga\Module\X509\Model\X509Target;
use ipl\Orm\Model;
use ipl\Sql\Connection;
use ipl\Sql\Expression;
use ipl\Sql\Select;
Expand Down Expand Up @@ -244,7 +245,7 @@ public static function findOrInsertCert(Connection $db, $cert)
if (! isset($certInfo['subject']['CN']) && ! empty($sans)) {
$subject = current($sans)[0];
} else {
$subject = static::shortNameFromDN($certInfo['subject']);
$subject = self::shortNameFromDN($certInfo['subject']);
}

// TODO: https://github.com/Icinga/ipl-orm/pull/78
Expand Down Expand Up @@ -330,7 +331,7 @@ private static function findOrInsertDn($db, $certInfo, $type)
}

foreach ($values as $value) {
$data .= "{$key}=${value}, ";
$data .= "$key=$value, ";
}
}
$hash = hash('sha256', $data, true);
Expand Down Expand Up @@ -442,7 +443,7 @@ public static function verifyCertificates(Connection $db)
));

$contents = [];

/** @var Model $ca */
foreach ($cas as $ca) {
$contents[] = $ca->certificate;
}
Expand Down
4 changes: 2 additions & 2 deletions library/X509/Common/JobUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ public static function addrToNumber(string $addr): ?GMP
* @param $num
* @param bool $ipv6
*
* @return ?string
* @return false|string
*/
public static function numberToAddr($num, bool $ipv6 = true): ?string
public static function numberToAddr($num, bool $ipv6 = true)
{
if ($ipv6) {
return inet_ntop(str_pad(gmp_export($num), 16, "\0", STR_PAD_LEFT));
Expand Down
4 changes: 1 addition & 3 deletions library/X509/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@
class Controller extends CompatController
{
use Database;
use SearchControls {
SearchControls::createSearchBar as private webCreateSearchBar;
}
use SearchControls;

/** @var Filter\Rule */
protected $filter;
Expand Down
2 changes: 1 addition & 1 deletion library/X509/Hook/SniHook.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ public static function getAll()
// the caller is expected to handle it as map of sequences though
$sni = [];

/** @var self $hook */
foreach (Hook::all('X509\Sni') as $hook) {
/** @var self $hook */
foreach ($hook->getHosts() as $ip => $hostname) {
$sni[$ip][$hostname] = $hostname;
}
Expand Down
14 changes: 8 additions & 6 deletions library/X509/Job.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ class Job implements Task
/** @var DateTime A formatted date time of this job start time */
protected $jobRunStart;

/** @var array A list of excluded IP addresses and host names */
/** @var ?array A list of excluded IP addresses and host names */
protected $excludedTargets = null;

/** @var DateTime Since last scan threshold used to filter out scan targets */
/** @var ?DateTime Since last scan threshold used to filter out scan targets */
protected $sinceLastScan;

/** @var bool Whether job run should only perform a rescan */
Expand Down Expand Up @@ -358,14 +358,14 @@ private function startNextTarget()
$this->pendingTargets++;

$url = "tls://[{$target->ip}]:{$target->port}";
Logger::debug("Connecting to %s", static::formatTarget($target));
Logger::debug("Connecting to %s", self::formatTarget($target));

/** @var ConnectorInterface $connector */
/** @var StreamOptsCaptureConnector $streamCapture */
list($connector, $streamCapture) = $this->getConnector($target->hostname);
$connector->connect($url)->then(
function (ConnectionInterface $conn) use ($target, $streamCapture) {
Logger::info("Connected to %s", static::formatTarget($target));
Logger::info("Connected to %s", self::formatTarget($target));

// Close connection in order to capture stream context options
$conn->close();
Expand Down Expand Up @@ -465,7 +465,9 @@ public function run(): Promise\ExtendedPromiseInterface
}
});

return $this->deferred->promise();
/** @var Promise\ExtendedPromiseInterface $promise */
$promise = $this->deferred->promise();
return $promise;
}

protected function processChain($target, $chain)
Expand Down Expand Up @@ -540,7 +542,7 @@ protected function processChain($target, $chain)
$chainUptodate = $currentFingerprints === $lastFingerprintsArr;
}

if ($chainUptodate) {
if ($lastChain && $chainUptodate) {
$chainId = $lastChain->id;
} else {
// TODO: https://github.com/Icinga/ipl-orm/pull/78
Expand Down
1 change: 1 addition & 0 deletions library/X509/ProvidedHook/HostsImportSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public function fetchData()

$results = [];
$foundDupes = [];
/** @var X509Target $target */
foreach ($targets as $target) {
$isV6 = Job::isIPV6($target->ip);
$target->host_ip = $target->ip;
Expand Down
1 change: 1 addition & 0 deletions library/X509/ProvidedHook/ServicesImportSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public function fetchData()
$targets->withColumns(['cert_subject_alt_name' => new Sql\Expression("$select", null, ...$values)]);

$results = [];
/** @var X509Target $target */
foreach ($targets as $target) {
$isV6 = Job::isIPV6($target->ip);
$target->host_ip = $target->ip;
Expand Down
47 changes: 0 additions & 47 deletions library/X509/SortAdapter.php

This file was deleted.

3 changes: 2 additions & 1 deletion library/X509/Web/Control/SearchBar/ObjectSuggestions.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class ObjectSuggestions extends Suggestions
public function setModel($model): self
{
if (is_string($model)) {
/** @var Model $model */
$model = new $model();
}

Expand Down Expand Up @@ -168,8 +169,8 @@ public static function collectFilterColumns(Model $model, Resolver $resolver)
self::collectRelations($resolver, $model, $models, []);
}

/** @var Model $targetModel */
foreach ($models as $path => $targetModel) {
/** @var Model $targetModel */
foreach ($resolver->getColumnDefinitions($targetModel) as $columnName => $definition) {
yield "$path.$columnName" => $definition->getLabel();
}
Expand Down
Loading