Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions .php-cs-fixer.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
<?php

use PhpCsFixer\Finder;
use PhpCsFixer\Config;
use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;

/**
* -------------------------------------------------------------------------
* Carbon plugin for GLPI
Expand Down Expand Up @@ -30,7 +34,7 @@
* -------------------------------------------------------------------------
*/

$finder = (new PhpCsFixer\Finder())
$finder = (new Finder())
->in(__DIR__)
->exclude([
'.git/',
Expand All @@ -41,9 +45,9 @@
])
;

return (new PhpCsFixer\Config())
return (new Config())
->setUnsupportedPhpVersionAllowed(true) // allow upcoming PHP versions
->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect())
->setParallelConfig(ParallelConfigFactory::detect())
->setCacheFile('files/_cache/php-cs-fixer/php-cs-fixer.cache')
->setRules([
'@PER-CS3.0' => true,
Expand Down
10 changes: 6 additions & 4 deletions .twig_cs.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@

declare(strict_types=1);

use FriendsOfTwig\Twigcs;
use FriendsOfTwig\Twigcs\Finder\TemplateFinder;
use FriendsOfTwig\Twigcs\Config\Config;
use Glpi\Tools\GlpiTwigRuleset;

$finder = Twigcs\Finder\TemplateFinder::create()
$finder = TemplateFinder::create()
->in(__DIR__ . '/templates')
->depth('>= 0')
->name('*.html.twig')
->ignoreVCSIgnored(true);

return Twigcs\Config\Config::create()
return Config::create()
->setFinder($finder)
->setRuleSet(\Glpi\Tools\GlpiTwigRuleset::class)
->setRuleSet(GlpiTwigRuleset::class)
;
15 changes: 8 additions & 7 deletions install/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

namespace GlpiPlugin\Carbon;

use RuntimeException;
use Config;
use DBmysql;
use DirectoryIterator;
Expand Down Expand Up @@ -112,7 +113,7 @@ public function install(array $args = []): bool

try {
$DB->runFile($dbFile);
} catch (\RuntimeException $e) {
} catch (RuntimeException $e) {
$this->migration->addWarningMessage("Error creating tables : " . $e->getMessage());
return false;
}
Expand Down Expand Up @@ -150,7 +151,7 @@ public function upgrade(string $from_version, array $args = []): bool
$current_version = $matches[1];
if (version_compare($db_version, $current_version) > 0) {
// database more recent than current version
$e = new \RuntimeException(sprintf(
$e = new RuntimeException(sprintf(
'Database of the plugin %s is more recent than the installed version %s.',
$db_version,
$current_version
Expand All @@ -167,19 +168,19 @@ public function upgrade(string $from_version, array $args = []): bool
// Check the version os SEMVER compliant
$regex = '!^' . self::SEMVER_REGEX . '$!';
if (preg_match($regex, $this->force_upgrade_from_version) !== 1) {
$e = new \RuntimeException('Invalid start version for upgrade.');
$e = new RuntimeException('Invalid start version for upgrade.');
trigger_error($e->getMessage(), E_USER_WARNING);
throw $e;
}
if (version_compare($this->force_upgrade_from_version, $oldest_upgradable_version) < 0) {
$e = new \RuntimeException('Upgrade is not supported before ' . $this->force_upgrade_from_version . '.');
$e = new RuntimeException('Upgrade is not supported before ' . $this->force_upgrade_from_version . '.');
trigger_error($e->getMessage(), E_USER_WARNING);
throw $e;
}
}
} else {
if (version_compare($from_version, $oldest_upgradable_version, 'lt')) {
$e = new \RuntimeException("Upgrade is not supported before $oldest_upgradable_version!");
$e = new RuntimeException("Upgrade is not supported before $oldest_upgradable_version!");
trigger_error($e->getMessage(), E_USER_WARNING);
throw $e;
}
Expand Down Expand Up @@ -288,7 +289,7 @@ public static function getOrCreateSource(string $name, int $fallback_level = 1,
'name' => $name,
]);
if ($source->isNewItem()) {
throw new \RuntimeException("Failed to create carbon intensity source '$name' in DB");
throw new RuntimeException("Failed to create carbon intensity source '$name' in DB");
}
return $source->getID();
}
Expand All @@ -310,7 +311,7 @@ public static function getOrCreateZone(string $name, int $source_id): int
]);
$zone->getFromDBByCrit(['name' => $name]);
if ($zone->isNewItem()) {
throw new \RuntimeException("Failed to create zone '$name' in DB");
throw new RuntimeException("Failed to create zone '$name' in DB");
}
return $zone->getID();
}
Expand Down
7 changes: 4 additions & 3 deletions install/Uninstall.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

namespace GlpiPlugin\Carbon;

use RuntimeException;
use Config;
use CronTask as GlpiCronTask;
use DBmysql;
Expand Down Expand Up @@ -68,7 +69,7 @@ private function deleteConfig()
{
$config = new Config();
if (!$config->deleteByCriteria(['context' => 'plugin:carbon'])) {
throw new \RuntimeException('Error while deleting config');
throw new RuntimeException('Error while deleting config');
}
}

Expand All @@ -80,7 +81,7 @@ private function deleteRights()
'name' => ['LIKE', 'carbon:%'],
])
) {
throw new \RuntimeException('Error while deleting rights');
throw new RuntimeException('Error while deleting rights');
}
}

Expand All @@ -102,7 +103,7 @@ private function deleteDisplayPrefs()
{
$displayPreference = new DisplayPreference();
if (!$displayPreference->deleteByCriteria(['itemtype' => CarbonIntensity::class])) {
throw new \RuntimeException('Error while deleting display preferences');
throw new RuntimeException('Error while deleting display preferences');
}
}

Expand Down
108 changes: 108 additions & 0 deletions rector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
<?php

/**
* -------------------------------------------------------------------------
* Carbon plugin for GLPI
*
* @copyright Copyright (C) 2024-2025 Teclib' and contributors.
* @license https://www.gnu.org/licenses/gpl-3.0.txt GPLv3+
* @link https://github.com/pluginsGLPI/carbon
*
* -------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of Carbon plugin for GLPI.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------------
*/

use Rector\Caching\ValueObject\Storage\FileCacheStorage;
use Rector\CodeQuality\Rector as CodeQuality;
use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector as DeadCode;
use Rector\ValueObject\PhpVersion;

require_once __DIR__ . '/../../src/Plugin.php';

return RectorConfig::configure()
->withPaths([
__DIR__ . '/ajax',
__DIR__ . '/front',
__DIR__ . '/install',
__DIR__ . '/public',
__DIR__ . '/src',
__DIR__ . '/tools',
])
->withPhpVersion(PhpVersion::PHP_82)
->withCache(
sys_get_temp_dir() . '/rector',
FileCacheStorage::class
)
->withParallel(300)
->withRootFiles()
->withImportNames(removeUnusedImports: true)
// FIXME apply it in another PR, it generates a huge diff ->withImportNames()
// ->withPreparedSets(
// deadCode: true,
// codeQuality: true,
// codingStyle: true,
// )
->withRules([
CodeQuality\Assign\CombinedAssignRector::class,
CodeQuality\BooleanAnd\RemoveUselessIsObjectCheckRector::class,
CodeQuality\BooleanAnd\SimplifyEmptyArrayCheckRector::class,
CodeQuality\BooleanNot\ReplaceMultipleBooleanNotRector::class,
CodeQuality\Catch_\ThrowWithPreviousExceptionRector::class,
CodeQuality\Empty_\SimplifyEmptyCheckOnEmptyArrayRector::class,
CodeQuality\Expression\InlineIfToExplicitIfRector::class,
CodeQuality\Expression\TernaryFalseExpressionToIfRector::class,
CodeQuality\For_\ForRepeatedCountToOwnVariableRector::class,
CodeQuality\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector::class,
CodeQuality\Foreach_\ForeachToInArrayRector::class,
CodeQuality\Foreach_\SimplifyForeachToCoalescingRector::class,
CodeQuality\Foreach_\UnusedForeachValueToArrayKeysRector::class,
CodeQuality\FuncCall\ChangeArrayPushToArrayAssignRector::class,
CodeQuality\FuncCall\CompactToVariablesRector::class,
CodeQuality\FuncCall\InlineIsAInstanceOfRector::class,
CodeQuality\FuncCall\IsAWithStringWithThirdArgumentRector::class,
CodeQuality\FuncCall\RemoveSoleValueSprintfRector::class,
CodeQuality\FuncCall\SetTypeToCastRector::class,
CodeQuality\FuncCall\SimplifyFuncGetArgsCountRector::class,
CodeQuality\FuncCall\SimplifyInArrayValuesRector::class,
CodeQuality\FuncCall\SimplifyStrposLowerRector::class,
CodeQuality\FuncCall\UnwrapSprintfOneArgumentRector::class,
CodeQuality\Identical\BooleanNotIdenticalToNotIdenticalRector::class,
CodeQuality\Identical\SimplifyArraySearchRector::class,
CodeQuality\Identical\SimplifyConditionsRector::class,
CodeQuality\Identical\StrlenZeroToIdenticalEmptyStringRector::class,
// FIXME apply it in another PR, it generates a huge diff CodeQuality\If_\CombineIfRector::class,
CodeQuality\If_\CompleteMissingIfElseBracketRector::class,
// FIXME apply it in another PR, it generates a huge diff CodeQuality\If_\ConsecutiveNullCompareReturnsToNullCoalesceQueueRector::class,
// FIXME apply it in another PR, it generates a huge diff CodeQuality\If_\ExplicitBoolCompareRector::class,
// FIXME apply it in another PR, it generates a huge diff CodeQuality\If_\ShortenElseIfRector::class,
// FIXME apply it in another PR, it generates a huge diff CodeQuality\If_\SimplifyIfElseToTernaryRector::class,
// FIXME apply it in another PR, it generates a huge diff CodeQuality\If_\SimplifyIfNotNullReturnRector::class,
// FIXME apply it in another PR, it generates a huge diff CodeQuality\If_\SimplifyIfNullableReturnRector::class,
// FIXME apply it in another PR, it generates a huge diff CodeQuality\If_\SimplifyIfReturnBoolRector::class,
CodeQuality\Include_\AbsolutizeRequireAndIncludePathRector::class,
CodeQuality\LogicalAnd\AndAssignsToSeparateLinesRector::class,
CodeQuality\LogicalAnd\LogicalToBooleanRector::class,
CodeQuality\NotEqual\CommonNotEqualRector::class,
CodeQuality\Ternary\UnnecessaryTernaryExpressionRector::class,
DeadCode\Assign\RemoveUnusedVariableAssignRector::class,
])
;
3 changes: 2 additions & 1 deletion src/AbstractImpact.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

namespace GlpiPlugin\Carbon;

use LogicException;
use CommonDBChild;
use CommonDBTM;
use DBmysql;
Expand Down Expand Up @@ -156,7 +157,7 @@ public static function getItemsToEvaluate(string $itemtype, array $crit = []): D

// Check $itemtype inherits from CommonDBTM
if (!GlpiToolbox::isCommonDBTM($itemtype)) {
throw new \LogicException('itemtype is not a CommonDBTM object');
throw new LogicException('itemtype is not a CommonDBTM object');
}

// clean $crit array: remove mostly SELECT, FROM
Expand Down
8 changes: 5 additions & 3 deletions src/CarbonIntensity.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@

namespace GlpiPlugin\Carbon;

use RuntimeException;
use Exception;
use CommonDropdown;
use DateInterval;
use DateTime;
Expand Down Expand Up @@ -318,7 +320,7 @@ public function save(string $zone_name, string $source_name, array $data): int
'name' => $source_name,
]);
if ($source->isNewItem()) {
throw new \RuntimeException('Attempt to save carbon intensity with a source which is not in the database');
throw new RuntimeException('Attempt to save carbon intensity with a source which is not in the database');
// trigger_error('Attempt to save carbon intensity with a source which is not in the database', E_USER_ERROR);
// return 0;
}
Expand All @@ -327,7 +329,7 @@ public function save(string $zone_name, string $source_name, array $data): int
'name' => $zone_name,
]);
if ($zone->isNewItem()) {
throw new \RuntimeException('Attempt to save carbon intensity with a zone which is not in the database');
throw new RuntimeException('Attempt to save carbon intensity with a zone which is not in the database');
// trigger_error('Attempt to save carbon intensity with a zone which is not in the database', E_USER_ERROR);
// return 0;
}
Expand Down Expand Up @@ -356,7 +358,7 @@ public function save(string $zone_name, string $source_name, array $data): int
);
$DB->executeStatement($stmt);
$count++;
} catch (\Exception $e) {
} catch (Exception $e) {
$count++;
continue;
}
Expand Down
9 changes: 5 additions & 4 deletions src/CronTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

namespace GlpiPlugin\Carbon;

use RuntimeException;
use CommonDBTM;
use CommonGLPI;
use Config as GlpiConfig;
Expand All @@ -54,7 +55,7 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)
// Delegate to the client's crontask class the tab name to return
// But keep here the logic to decide if a tab name shall be returned
// to reduce class loading
if (!is_a($item, GlpiCronTask::class)) {
if (!$item instanceof GlpiCronTask) {
return '';
}
if (!in_array($item->fields['itemtype'], CronTaskProvider::getCronTaskTypes())) {
Expand All @@ -66,7 +67,7 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)

public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
{
if (is_a($item, GlpiCronTask::class)) {
if ($item instanceof GlpiCronTask) {
/** @var GlpiCronTask $item */
$cron_task = new self();
$cron_task->showForCronTask($item);
Expand Down Expand Up @@ -284,7 +285,7 @@ public static function downloadCarbonIntensityFromSource(GlpiCronTask $task, Cli
$zone_name = $zone['name'];
try {
$added = $intensity->downloadOneZone($data_source, $zone_name, $limit_per_zone);
} catch (\RuntimeException $e) {
} catch (RuntimeException $e) {
trigger_error($e->getMessage(), E_USER_WARNING);
continue;
}
Expand Down Expand Up @@ -342,7 +343,7 @@ public function fillIncompleteLocations(GlpiCronTask $task): int
} catch (QuotaExceeded $e) {
// If the quota is exceeded, stop the task
break;
} catch (\RuntimeException $e) {
} catch (RuntimeException $e) {
// If there is a runtime exception, log it and continue
$failure = true;
trigger_error($e->getMessage(), E_USER_WARNING);
Expand Down
3 changes: 2 additions & 1 deletion src/Dashboard/Provider.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

namespace GlpiPlugin\Carbon\Dashboard;

use RuntimeException;
use CommonDBTM;
use Computer as GlpiComputer;
use ComputerModel as GlpiComputerModel;
Expand Down Expand Up @@ -850,7 +851,7 @@ public static function getCarbonIntensity(array $params): array
$count_request['COUNT'] = 'c';
$count = $DB->request($count_request);
if ($count->numrows() !== 1) {
throw new \RuntimeException("Failed to count carbon intensity samples");
throw new RuntimeException("Failed to count carbon intensity samples");
}
$date = CarbonIntensity::getTableField('date');
$intensity = CarbonIntensity::getTableField('intensity');
Expand Down
4 changes: 3 additions & 1 deletion src/DataSource/CarbonIntensity/AbortException.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,6 @@

namespace GlpiPlugin\Carbon\DataSource\CarbonIntensity;

class AbortException extends \RuntimeException {}
use RuntimeException;

class AbortException extends RuntimeException {}
Loading
Loading