diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index e556da5b..1ba95f81 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -1,5 +1,9 @@ in(__DIR__) ->exclude([ '.git/', @@ -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, diff --git a/.twig_cs.dist.php b/.twig_cs.dist.php index 772ee42b..589b7390 100644 --- a/.twig_cs.dist.php +++ b/.twig_cs.dist.php @@ -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) ; diff --git a/install/Install.php b/install/Install.php index 1d6e4065..26528486 100644 --- a/install/Install.php +++ b/install/Install.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon; +use RuntimeException; use Config; use DBmysql; use DirectoryIterator; @@ -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; } @@ -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 @@ -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; } @@ -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(); } @@ -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(); } diff --git a/install/Uninstall.php b/install/Uninstall.php index d1b0b8b2..59d5dec9 100644 --- a/install/Uninstall.php +++ b/install/Uninstall.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon; +use RuntimeException; use Config; use CronTask as GlpiCronTask; use DBmysql; @@ -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'); } } @@ -80,7 +81,7 @@ private function deleteRights() 'name' => ['LIKE', 'carbon:%'], ]) ) { - throw new \RuntimeException('Error while deleting rights'); + throw new RuntimeException('Error while deleting rights'); } } @@ -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'); } } diff --git a/rector.php b/rector.php new file mode 100644 index 00000000..4f04d7b5 --- /dev/null +++ b/rector.php @@ -0,0 +1,108 @@ +. + * + * ------------------------------------------------------------------------- + */ + +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, + ]) +; diff --git a/src/AbstractImpact.php b/src/AbstractImpact.php index b0e9646c..e41103ff 100644 --- a/src/AbstractImpact.php +++ b/src/AbstractImpact.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon; +use LogicException; use CommonDBChild; use CommonDBTM; use DBmysql; @@ -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 diff --git a/src/CarbonIntensity.php b/src/CarbonIntensity.php index 3f63c273..10ec7396 100644 --- a/src/CarbonIntensity.php +++ b/src/CarbonIntensity.php @@ -32,6 +32,8 @@ namespace GlpiPlugin\Carbon; +use RuntimeException; +use Exception; use CommonDropdown; use DateInterval; use DateTime; @@ -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; } @@ -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; } @@ -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; } diff --git a/src/CronTask.php b/src/CronTask.php index 332199a4..b9b603f7 100644 --- a/src/CronTask.php +++ b/src/CronTask.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon; +use RuntimeException; use CommonDBTM; use CommonGLPI; use Config as GlpiConfig; @@ -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())) { @@ -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); @@ -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; } @@ -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); diff --git a/src/Dashboard/Provider.php b/src/Dashboard/Provider.php index e8ca73be..be40b5b0 100644 --- a/src/Dashboard/Provider.php +++ b/src/Dashboard/Provider.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon\Dashboard; +use RuntimeException; use CommonDBTM; use Computer as GlpiComputer; use ComputerModel as GlpiComputerModel; @@ -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'); diff --git a/src/DataSource/CarbonIntensity/AbortException.php b/src/DataSource/CarbonIntensity/AbortException.php index 6e176584..f4b1ac64 100644 --- a/src/DataSource/CarbonIntensity/AbortException.php +++ b/src/DataSource/CarbonIntensity/AbortException.php @@ -32,4 +32,6 @@ namespace GlpiPlugin\Carbon\DataSource\CarbonIntensity; -class AbortException extends \RuntimeException {} +use RuntimeException; + +class AbortException extends RuntimeException {} diff --git a/src/DataSource/CarbonIntensity/AbstractClient.php b/src/DataSource/CarbonIntensity/AbstractClient.php index 01b668c1..37209b4d 100644 --- a/src/DataSource/CarbonIntensity/AbstractClient.php +++ b/src/DataSource/CarbonIntensity/AbstractClient.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon\DataSource\CarbonIntensity; +use Generator; use Config as GlpiConfig; use DateInterval; use DateTime; @@ -252,9 +253,9 @@ public function incrementalDownload(string $zone, DateTimeImmutable $start_date, * * @param DateTimeImmutable $start * @param DateTimeImmutable $stop - * @return \Generator + * @return Generator */ - protected function sliceDateRangeByMonth(DateTimeImmutable $start, DateTimeImmutable $stop): \Generator + protected function sliceDateRangeByMonth(DateTimeImmutable $start, DateTimeImmutable $stop): Generator { $real_start = $start->setTime((int) $start->format('H'), 0, 0, 0); $real_stop = $stop->setTime((int) $stop->format('H'), 0, 0, 0); @@ -298,7 +299,7 @@ protected function sliceDateRangeByMonth(DateTimeImmutable $start, DateTimeImmut * * @param DateTimeImmutable $start * @param DateTimeImmutable $stop - * @return \Generator + * @return Generator */ protected function sliceDateRangeByDay(DateTimeImmutable $start, DateTimeImmutable $stop) { diff --git a/src/DataSource/CarbonIntensity/ClientFactory.php b/src/DataSource/CarbonIntensity/ClientFactory.php index db5bcd75..9fc294bf 100644 --- a/src/DataSource/CarbonIntensity/ClientFactory.php +++ b/src/DataSource/CarbonIntensity/ClientFactory.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon\DataSource\CarbonIntensity; +use InvalidArgumentException; use GlpiPlugin\Carbon\DataSource\ConfigInterface; use GlpiPlugin\Carbon\DataSource\RestApiClient; @@ -119,7 +120,7 @@ public static function create(string $type): AbstractClient { $client_classes = self::getClientTypes(); if (!isset($client_classes[$type])) { - throw new \InvalidArgumentException("Unknown client type: $type"); + throw new InvalidArgumentException("Unknown client type: $type"); } $class_name = $client_classes[$type]; @@ -137,7 +138,7 @@ public static function createByName(string $name): AbstractClient { $names = self::getClientNames(); if (!in_array($name, $names)) { - throw new \InvalidArgumentException("Unknown client type name: $name"); + throw new InvalidArgumentException("Unknown client type name: $name"); } $class_name = array_search($name, $names); diff --git a/src/DataSource/CarbonIntensity/ElectricityMaps/Client.php b/src/DataSource/CarbonIntensity/ElectricityMaps/Client.php index 7402e252..e1e0840f 100644 --- a/src/DataSource/CarbonIntensity/ElectricityMaps/Client.php +++ b/src/DataSource/CarbonIntensity/ElectricityMaps/Client.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon\DataSource\CarbonIntensity\ElectricityMaps; +use RuntimeException; use DateInterval; use DateTime; use DateTimeImmutable; @@ -112,7 +113,7 @@ public function createZones(): int try { $zones = $this->queryZones(); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { return 0; } diff --git a/src/DataSource/Lca/Boaviztapi/Client.php b/src/DataSource/Lca/Boaviztapi/Client.php index 6ee8680a..2c57d836 100644 --- a/src/DataSource/Lca/Boaviztapi/Client.php +++ b/src/DataSource/Lca/Boaviztapi/Client.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon\DataSource\Lca\Boaviztapi; +use RuntimeException; use DBmysql; use Dropdown; use GlpiPlugin\Carbon\Config as CarbonConfig; @@ -84,7 +85,7 @@ public function __construct(RestApiClientInterface $client, string $url = '') } else { $url = CarbonConfig::getPluginConfigurationValue('boaviztapi_base_url'); if (!is_string($url) || $url === '') { - throw new \RuntimeException('Invalid Boaviztapi base URL'); + throw new RuntimeException('Invalid Boaviztapi base URL'); } $this->base_url = $url; } diff --git a/src/DataSource/Lca/Boaviztapi/Config.php b/src/DataSource/Lca/Boaviztapi/Config.php index 09fa096b..aff4dc0e 100644 --- a/src/DataSource/Lca/Boaviztapi/Config.php +++ b/src/DataSource/Lca/Boaviztapi/Config.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon\DataSource\Lca\Boaviztapi; +use Exception; use GlpiPlugin\Carbon\Config as PluginConfig; use GlpiPlugin\Carbon\DataSource\ConfigInterface; use GlpiPlugin\Carbon\DataSource\RestApiClient; @@ -87,14 +88,14 @@ public function getConfigTemplate(): string public function configUpdate(array $input): array { - if (isset($input['boaviztapi_base_url']) && strlen($input['boaviztapi_base_url']) > 0) { + if (isset($input['boaviztapi_base_url']) && (string) $input['boaviztapi_base_url'] !== '') { $old_url = PluginConfig::getPluginConfigurationValue('boaviztapi_base_url'); if ($old_url != $input['boaviztapi_base_url']) { $boavizta = new Client(new RestApiClient(), $input['boaviztapi_base_url']); $zones = []; try { $zones = $boavizta->queryZones(); - } catch (\Exception $e) { + } catch (Exception $e) { unset($input['boaviztapi_base_url']); Session::addMessageAfterRedirect(__('Invalid Boavizta API URL', 'carbon'), false, ERROR); } diff --git a/src/DataSource/Lca/ClientFactory.php b/src/DataSource/Lca/ClientFactory.php index fbe9abfe..3d373dd2 100644 --- a/src/DataSource/Lca/ClientFactory.php +++ b/src/DataSource/Lca/ClientFactory.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon\DataSource\Lca; +use InvalidArgumentException; use GlpiPlugin\Carbon\DataSource\ConfigInterface; use GlpiPlugin\Carbon\DataSource\RestApiClient; @@ -120,7 +121,7 @@ public static function create(string $type): AbstractClient $type .= 'Client'; $client_classes = self::getClientTypes(); if (!isset($client_classes[$type])) { - throw new \InvalidArgumentException("Unknown client type: $type"); + throw new InvalidArgumentException("Unknown client type: $type"); } $class_name = $client_classes[$type]; @@ -138,7 +139,7 @@ public static function createByName(string $name): AbstractClient { $names = self::getClientNames(); if (!in_array($name, $names)) { - throw new \InvalidArgumentException("Unknown client type name: $name"); + throw new InvalidArgumentException("Unknown client type name: $name"); } $class_name = array_search($name, $names); diff --git a/src/DataSource/RestApiClient.php b/src/DataSource/RestApiClient.php index d66df422..4e261abd 100644 --- a/src/DataSource/RestApiClient.php +++ b/src/DataSource/RestApiClient.php @@ -32,9 +32,9 @@ namespace GlpiPlugin\Carbon\DataSource; +use GuzzleHttp\Psr7\Message; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; -use GuzzleHttp\Psr7; use Toolbox; class RestApiClient implements RestApiClientInterface @@ -73,10 +73,10 @@ public function request(string $method = 'GET', string $uri = '', array $options $this->last_error = [ 'title' => "Plugins API error", 'exception' => $e->getMessage(), - 'request' => Psr7\Message::toString($e->getRequest()), + 'request' => Message::toString($e->getRequest()), ]; if ($e->hasResponse()) { - $this->last_error['response'] = Psr7\Message::toString($e->getResponse()); + $this->last_error['response'] = Message::toString($e->getResponse()); } Toolbox::logDebug($this->last_error); diff --git a/src/Engine/V1/AbstractAsset.php b/src/Engine/V1/AbstractAsset.php index a86f407a..9a72ca67 100644 --- a/src/Engine/V1/AbstractAsset.php +++ b/src/Engine/V1/AbstractAsset.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon\Engine\V1; +use LogicException; use CommonDBTM; use DateInterval; use DateTimeImmutable; @@ -65,10 +66,10 @@ public function __construct(CommonDBTM $item) ]; foreach ($types as $type) { if ($type === '') { - throw new \LogicException('Itemtype not set'); + throw new LogicException('Itemtype not set'); } if (!is_subclass_of($type, CommonDBTM::class)) { - throw new \LogicException('Itemtype does not inherits from ' . CommonDBTM::class); + throw new LogicException('Itemtype does not inherits from ' . CommonDBTM::class); } } diff --git a/src/Impact/Embodied/AbstractEmbodiedImpact.php b/src/Impact/Embodied/AbstractEmbodiedImpact.php index 36bb383e..770425dc 100644 --- a/src/Impact/Embodied/AbstractEmbodiedImpact.php +++ b/src/Impact/Embodied/AbstractEmbodiedImpact.php @@ -33,6 +33,8 @@ namespace GlpiPlugin\Carbon\Impact\Embodied; +use LogicException; +use RuntimeException; use CommonDBTM; use DBmysql; use DBmysqlIterator; @@ -67,7 +69,7 @@ abstract class AbstractEmbodiedImpact implements EmbodiedImpactInterface public function __construct(CommonDBTM $item) { if ($item->isNewItem()) { - throw new \LogicException("Given item is empty"); + throw new LogicException("Given item is empty"); } $this->item = $item; foreach (array_flip(Type::getImpactTypes()) as $type) { @@ -129,7 +131,7 @@ public function evaluateItem(): bool } catch (ConnectException $e) { Session::addMessageAfterRedirect(__('Connection to Boavizta failed.', 'carbon'), false, ERROR); return false; - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { Session::addMessageAfterRedirect(__('Embodied impact evaluation falied.', 'carbon'), false, ERROR); return false; } diff --git a/src/Impact/Embodied/Boavizta/AbstractAsset.php b/src/Impact/Embodied/Boavizta/AbstractAsset.php index 4223ce4d..b5504692 100644 --- a/src/Impact/Embodied/Boavizta/AbstractAsset.php +++ b/src/Impact/Embodied/Boavizta/AbstractAsset.php @@ -33,6 +33,7 @@ namespace GlpiPlugin\Carbon\Impact\Embodied\Boavizta; +use RuntimeException; use GlpiPlugin\Carbon\DataSource\Lca\Boaviztapi\Client; use GlpiPlugin\Carbon\Impact\Embodied\AbstractEmbodiedImpact; @@ -81,7 +82,7 @@ protected function getVersion(): string try { $response = $this->client->get('utils/version'); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { trigger_error($e->getMessage(), E_USER_WARNING); throw $e; } @@ -90,7 +91,7 @@ protected function getVersion(): string 'Invalid response from Boavizta API: %s', json_encode($response[0] ?? '') ), E_USER_WARNING); - throw new \RuntimeException('Invalid response from Boavizta API'); + throw new RuntimeException('Invalid response from Boavizta API'); } self::$engine_version = $response[0]; return self::$engine_version; @@ -119,7 +120,7 @@ protected function query(array $description): array $response = $this->client->post($this->endpoint, [ 'json' => $description, ]); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { trigger_error($e->getMessage(), E_USER_WARNING); throw $e; } diff --git a/src/Impact/Embodied/Engine.php b/src/Impact/Embodied/Engine.php index c7b9185c..a3350028 100644 --- a/src/Impact/Embodied/Engine.php +++ b/src/Impact/Embodied/Engine.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon\Impact\Embodied; +use RuntimeException; use CommonDBTM; use CommonGLPI; use DBmysql; @@ -82,7 +83,7 @@ public static function getEngineFromItemtype(CommonDBTM $item): ?EmbodiedImpactI $embodied_impact = new $embodied_impact_class($item); try { return self::configureEngine($embodied_impact); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { // If the engine cannot be configured, it is not usable return null; } diff --git a/src/Impact/History/AbstractAsset.php b/src/Impact/History/AbstractAsset.php index c4834965..73603210 100644 --- a/src/Impact/History/AbstractAsset.php +++ b/src/Impact/History/AbstractAsset.php @@ -33,6 +33,7 @@ namespace GlpiPlugin\Carbon\Impact\History; +use Exception; use CommonDBTM; use DateInterval; use DateTime; @@ -363,7 +364,7 @@ public function calculateImpact(int $items_id): bool { try { $calculated = $this->evaluateItem($items_id); - } catch (\Exception $e) { + } catch (Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); Session::addMessageAfterRedirect( __('Error while calculating impact', 'carbon'), diff --git a/src/Impact/Usage/AbstractUsageImpact.php b/src/Impact/Usage/AbstractUsageImpact.php index 94c3dbc1..5dfda85a 100644 --- a/src/Impact/Usage/AbstractUsageImpact.php +++ b/src/Impact/Usage/AbstractUsageImpact.php @@ -33,6 +33,8 @@ namespace GlpiPlugin\Carbon\Impact\Usage; +use LogicException; +use RuntimeException; use CommonDBTM; use DBmysql; use DBmysqlIterator; @@ -65,7 +67,7 @@ abstract class AbstractUsageImpact implements UsageImpactInterface public function __construct(CommonDBTM $item) { if ($item->isNewItem()) { - throw new \LogicException("Given item is empty"); + throw new LogicException("Given item is empty"); } $this->item = $item; foreach (array_flip(Type::getImpactTypes()) as $type) { @@ -107,7 +109,7 @@ public function getItemsToEvaluate(string $itemtype, array $crit = []): DBmysqlI global $DB; if (!GlpiToolbox::isCommonDBTM($itemtype)) { - throw new \LogicException('Itemtype does not inherits from ' . CommonDBTM::class); + throw new LogicException('Itemtype does not inherits from ' . CommonDBTM::class); } $crit[] = [ @@ -163,7 +165,7 @@ public function evaluateItem(): bool try { $this->getVersion(); $impacts = $this->doEvaluation($this->item); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { return false; } diff --git a/src/Impact/Usage/Boavizta/AbstractAsset.php b/src/Impact/Usage/Boavizta/AbstractAsset.php index 2226da1e..ddf08b9a 100644 --- a/src/Impact/Usage/Boavizta/AbstractAsset.php +++ b/src/Impact/Usage/Boavizta/AbstractAsset.php @@ -33,11 +33,10 @@ namespace GlpiPlugin\Carbon\Impact\Usage\Boavizta; +use RuntimeException; use CommonDBTM; use DbUtils; use GlpiPlugin\Carbon\DataSource\Lca\Boaviztapi\Client; -use GlpiPlugin\Carbon\DataTracking\TrackedFloat; -use GlpiPlugin\Carbon\Impact\Type; use GlpiPlugin\Carbon\Impact\Usage\AbstractUsageImpact; use GlpiPlugin\Carbon\Location; use GlpiPlugin\Carbon\UsageImpact; @@ -101,7 +100,7 @@ protected function getVersion(): string try { $response = $this->client->get('utils/version'); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { trigger_error($e->getMessage(), E_USER_WARNING); throw $e; } @@ -110,7 +109,7 @@ protected function getVersion(): string 'Invalid response from Boavizta API: %s', json_encode($response[0] ?? '') ), E_USER_WARNING); - throw new \RuntimeException('Invalid response from Boavizta API'); + throw new RuntimeException('Invalid response from Boavizta API'); } self::$engine_version = $response[0]; return self::$engine_version; @@ -133,7 +132,7 @@ protected function query($description): array $response = $this->client->post($this->endpoint, [ 'json' => $description, ]); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { trigger_error($e->getMessage(), E_USER_WARNING); throw $e; } diff --git a/src/Impact/Usage/Boavizta/Monitor.php b/src/Impact/Usage/Boavizta/Monitor.php index 6c8d3171..e927f3f3 100644 --- a/src/Impact/Usage/Boavizta/Monitor.php +++ b/src/Impact/Usage/Boavizta/Monitor.php @@ -39,7 +39,6 @@ use DbUtils; use Glpi\Asset\Asset_PeripheralAsset; use Glpi\DBAL\QueryExpression; -use GlpiPlugin\Carbon\MonitorType; use Monitor as GlpiMonitor; use MonitorModel as GlpiMonitorModel; use MonitorType as GlpiMonitorType; @@ -58,12 +57,9 @@ public function getEvaluableQuery(string $itemtype, array $crit = [], bool $enti // the location should behandled like done in History namespace $item_table = self::$itemtype::getTable(); - $item_model_table = self::$model_itemtype::getTable(); + self::$model_itemtype::getTable(); $assets_items_table = Asset_PeripheralAsset::getTable(); $computers_table = GlpiComputer::getTable(); - $glpi_monitor_types_table = GlpiMonitorType::getTable(); - $glpi_monitor_types_fk = GlpiMonitorType::getForeignKeyField(); - $monitor_types_table = MonitorType::getTable(); $request = parent::getEvaluableQuery($itemtype); $parent_inner_joins = $request['INNER JOIN']; diff --git a/src/Impact/Usage/Engine.php b/src/Impact/Usage/Engine.php index 7e3aa6d1..54198fb9 100644 --- a/src/Impact/Usage/Engine.php +++ b/src/Impact/Usage/Engine.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon\Impact\Usage; +use RuntimeException; use CommonDBTM; use CommonGLPI; use GlpiPlugin\Carbon\Config; @@ -72,7 +73,7 @@ public static function getEngineFromItemtype(CommonDBTM $item): ?AbstractUsageIm $usage_impact = new $usage_impact_class($item); try { return self::configureEngine($usage_impact); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { return null; } } diff --git a/src/Impact/Usage/UsageImpactInterface.php b/src/Impact/Usage/UsageImpactInterface.php index 55f83492..2d934ba1 100644 --- a/src/Impact/Usage/UsageImpactInterface.php +++ b/src/Impact/Usage/UsageImpactInterface.php @@ -35,7 +35,6 @@ use CommonDBTM; use DBmysqlIterator; -use GlpiPlugin\Carbon\Engine\V1\EngineInterface; interface UsageImpactInterface { diff --git a/src/Location.php b/src/Location.php index 1c153d70..cfd48db0 100644 --- a/src/Location.php +++ b/src/Location.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon; +use LogicException; use CommonDBChild; use CommonDBTM; use CommonGLPI; @@ -68,7 +69,7 @@ public static function getIcon() public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { - if (is_a($item, GlpiLocation::class)) { + if ($item instanceof GlpiLocation) { return self::createTabEntry(__('Environmental impact', 'carbon'), 0); } return ''; @@ -76,7 +77,7 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) { - if (is_a($item, GlpiLocation::class)) { + if ($item instanceof GlpiLocation) { /** @var GlpiLocation $item */ $location = new self(); $location->showForLocation($item); @@ -660,6 +661,6 @@ public static function getZoneCode(CommonDBTM $item, ?DateTime $date = null): ?s return $location->fields['boavizta_zone']; } - throw new \LogicException('Not implemented yet'); + throw new LogicException('Not implemented yet'); } } diff --git a/src/Toolbox.php b/src/Toolbox.php index 33600302..dc373a50 100644 --- a/src/Toolbox.php +++ b/src/Toolbox.php @@ -32,6 +32,7 @@ namespace GlpiPlugin\Carbon; +use InvalidArgumentException; use DateInterval; use DateTime; use DateTimeImmutable; @@ -507,7 +508,7 @@ public static function findTemporalGapsInTable(string $table, DateTimeInterface global $DB; if ($interval->m !== 0 || $interval->y !== 0) { - throw new \InvalidArgumentException('Interval must be in days, hours, minutes or seconds'); + throw new InvalidArgumentException('Interval must be in days, hours, minutes or seconds'); } if ($stop === null) { // Assume stop date is yesterday at midnight