Skip to content

Commit

Permalink
Symfony compliant error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierstoval authored and cedric-anne committed Jan 23, 2025
1 parent b52e5de commit 576fcd0
Show file tree
Hide file tree
Showing 61 changed files with 1,358 additions and 1,383 deletions.
24 changes: 0 additions & 24 deletions .phpstan-baseline.php
Original file line number Diff line number Diff line change
Expand Up @@ -1735,12 +1735,6 @@
'count' => 1,
'path' => __DIR__ . '/src/Fieldblacklist.php',
];
$ignoreErrors[] = [
'message' => '#^Property GLPI\\:\\:\\$error_handler is unused\\.$#',
'identifier' => 'property.unused',
'count' => 1,
'path' => __DIR__ . '/src/GLPI.php',
];
$ignoreErrors[] = [
'message' => '#^Method GLPIKey\\:\\:keyExists\\(\\) should return string but returns bool\\.$#',
'identifier' => 'return.type',
Expand Down Expand Up @@ -2065,24 +2059,6 @@
'count' => 1,
'path' => __DIR__ . '/src/Glpi/Api/HL/Search.php',
];
$ignoreErrors[] = [
'message' => '#^Instanceof between Psr\\\\Log\\\\LoggerInterface and Psr\\\\Log\\\\LoggerInterface will always evaluate to true\\.$#',
'identifier' => 'instanceof.alwaysTrue',
'count' => 1,
'path' => __DIR__ . '/src/Glpi/Application/ErrorHandler.php',
];
$ignoreErrors[] = [
'message' => '#^Property Glpi\\\\Application\\\\ErrorHandler\\:\\:\\$exit_code is never read, only written\\.$#',
'identifier' => 'property.onlyWritten',
'count' => 1,
'path' => __DIR__ . '/src/Glpi/Application/ErrorHandler.php',
];
$ignoreErrors[] = [
'message' => '#^Strict comparison using \\!\\=\\= between null and \'comment\'\\|\'error\' will always evaluate to true\\.$#',
'identifier' => 'notIdentical.alwaysTrue',
'count' => 1,
'path' => __DIR__ . '/src/Glpi/Application/ErrorHandler.php',
];
$ignoreErrors[] = [
'message' => '#^Strict comparison using \\=\\=\\= between null and 2 will always evaluate to false\\.$#',
'identifier' => 'identical.alwaysFalse',
Expand Down
7 changes: 3 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,6 @@ The present file will list all changes made to the project; according to the
- `Glpi\Dashboard\Filters\AbstractFilter::field()` method has been made protected.
- Usage of `CommonITILValidation::dropdownValidator()` with the `name` and `users_id_validate` options are no longer supported. Use `prefix` and `itemtype_target`/`items_id_target` respectively instead.
- The `helper` property of form fields will not support anymore the presence of HTML code.
- `Glpi\Application\ErrorHandler` constructor visibility has been changed to private.
- `GLPI::initErrorHandler()` does not return any value anymore.
- The `inc/autoload.function.php`, `inc/based_config.php`, `inc/config.php`, `inc/db.function.php` and `inc/define.php` files have been removed and the `inc/includes.php` file has been almost emptied.
The corresponding global functions, constants and variables are now loaded and initialized automatically and the corresponding GLPI boostraping logic is now executed automatically.
Expand Down Expand Up @@ -397,11 +396,11 @@ The present file will list all changes made to the project; according to the
- `FieldUnicity::showDebug()`
- `GLPI::getErrorHandler()`
- `GLPI::getLogLevel()`
- `GLPI::initErrorHandler()`
- `GLPI::initLogger()`
- `Glpi\Api\API::showDebug()`
- `Glpi\Api\API::returnSanitizedContent()`
- `Glpi\Application\ErrorHandler::handleSqlError()`
- `Glpi\Application\ErrorHandler::handleSqlWarnings()`
- `Glpi\Application\ErrorHandler::handleTwigError()`
- `Glpi\Application\ErrorHandler` class
- `Glpi\Console\Command\ForceNoPluginsOptionCommandInterface` class
- `Glpi\Dashboard\Filter::dates()`
- `Glpi\Dashboard\Filter::dates_mod()`
Expand Down
5 changes: 2 additions & 3 deletions ajax/dashboard.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@
* ---------------------------------------------------------------------
*/

use Glpi\Application\ErrorHandler;
use Glpi\Dashboard\Grid;
use Glpi\Error\ErrorHandler;
use Glpi\Exception\Http\AccessDeniedHttpException;

if (!isset($_REQUEST["action"])) {
Expand Down Expand Up @@ -208,8 +208,7 @@
$result[$card['card_id']] = $grid->getCardHtml($card['card_id'], array_merge($request_data, $card));
} catch (\Throwable $e) {
// Send exception to logger without actually exiting.
// Use quiet mode to not break JSON result.
ErrorHandler::getInstance()->handleException($e, true);
ErrorHandler::logCaughtException($e);
}
}
\Glpi\Debug\Profiler::getInstance()->stop('Get cards HTML');
Expand Down
3 changes: 0 additions & 3 deletions ajax/debug.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
* ---------------------------------------------------------------------
*/

use Glpi\Application\ErrorHandler;
use Glpi\Exception\Http\AccessDeniedHttpException;
use Glpi\Exception\Http\BadRequestHttpException;
use Glpi\Exception\Http\NotFoundHttpException;
Expand Down Expand Up @@ -99,8 +98,6 @@
echo '[]';
return;
}
// In some cases, a class that isn't a proper itemtype may show in the selection box and this would trigger a SQL error that cannot be caught.
ErrorHandler::getInstance()->disableOutput();
try {
/** @var CommonGLPI $item */
$item = new $_GET['itemtype']();
Expand Down
5 changes: 0 additions & 5 deletions ajax/fileupload.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,4 @@
* @since 9.2
*/

use Glpi\Application\ErrorHandler;

// Ensure warnings will not break ajax output.
ErrorHandler::getInstance()->disableOutput();

GLPIUploadHandler::uploadFiles($_POST);
13 changes: 7 additions & 6 deletions dependency_injection/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Glpi\DependencyInjection\PublicService;
use Glpi\Log\LegacyGlobalLogger;
use Glpi\Error\ErrorHandler;

return static function (ContainerConfigurator $container): void {
$projectDir = dirname(__DIR__);
Expand All @@ -47,6 +47,9 @@
$parameters->set('env(APP_SECRET_FILE)', $projectDir . '/config/glpicrypt.key');
$parameters->set('kernel.secret', env('default:glpi.default_secret:file:APP_SECRET_FILE'));

// Prevent low level errors (e.g. warning) to be converted to exception in dev environment
$parameters->set('debug.error_handler.throw_at', ErrorHandler::FATAL_ERRORS);

$services = $services
->defaults()
->autowire()
Expand All @@ -64,9 +67,7 @@
$projectDir . '/src/Glpi/Form/ConditionalVisiblity/*Manager.php'
);

/**
* Override Symfony's logger.
* @see \Symfony\Component\HttpKernel\DependencyInjection\LoggerPass
*/
$services->set('logger', LegacyGlobalLogger::class);
// Prevent Symfony to register its own default logger.
// @see \Symfony\Component\HttpKernel\DependencyInjection\LoggerPass
$services->set('logger')->synthetic();
};
4 changes: 0 additions & 4 deletions front/css.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
* ---------------------------------------------------------------------
*/

use Glpi\Application\ErrorHandler;
use Glpi\UI\ThemeManager;

// Main CSS compilation requires about 70MB of memory.
Expand All @@ -43,9 +42,6 @@
ini_set('memory_limit', sprintf('%dM', $max_memory));
}

// Ensure warnings will not break CSS output.
ErrorHandler::getInstance()->disableOutput();

// If a custom theme is requested, we need to get the real path of the theme
if (isset($_GET['file']) && isset($_GET['is_custom_theme']) && $_GET['is_custom_theme']) {
$theme = ThemeManager::getInstance()->getTheme($_GET['file']);
Expand Down
4 changes: 2 additions & 2 deletions front/locale.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
* ---------------------------------------------------------------------
*/

use Glpi\Application\ErrorHandler;
use Glpi\Error\ErrorHandler;

/**
* @var array $CFG_GLPI
Expand Down Expand Up @@ -78,7 +78,7 @@
$messages = $TRANSLATE->getAllMessages($_GET['domain']);
} catch (\Throwable $e) {
// Error may happen when overrided translation files does not use same plural rules as GLPI.
ErrorHandler::getInstance()->handleException($e, true);
ErrorHandler::logCaughtException($e);
}
if (!($messages instanceof \Laminas\I18n\Translator\TextDomain)) {
// No TextDomain found means that there is no translations for given domain.
Expand Down
4 changes: 2 additions & 2 deletions front/notificationmailingsetting.form.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
* ---------------------------------------------------------------------
*/

use Glpi\Application\ErrorHandler;
use Glpi\Error\ErrorHandler;
use Glpi\Event;
use Glpi\Mail\SMTP\OauthConfig;

Expand All @@ -58,7 +58,7 @@
$_SESSION['smtp_oauth2_state'] = $provider->getState();
Html::redirect($auth_url);
} catch (\Throwable $e) {
ErrorHandler::getInstance()->handleException($e, true);
ErrorHandler::logCaughtException($e);
Session::addMessageAfterRedirect(
htmlescape(sprintf(_x('oauth', 'Authorization failed with error: %s'), $e->getMessage())),
false,
Expand Down
4 changes: 0 additions & 4 deletions front/palette_preview.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,8 @@
* ---------------------------------------------------------------------
*/

use Glpi\Application\ErrorHandler;
use Glpi\UI\ThemeManager;

// Ensure warnings will not break image output.
ErrorHandler::getInstance()->disableOutput();

$theme = ThemeManager::getInstance()->getTheme($_GET['key']);
$preview = $theme !== null ? $theme->getPreviewPath(false) : null;

Expand Down
12 changes: 4 additions & 8 deletions install/install.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,6 @@ function step2($update)
function step3($host, $user, $password, $update)
{

error_reporting(16);
mysqli_report(MYSQLI_REPORT_OFF);

//Check if the port is in url
Expand Down Expand Up @@ -482,13 +481,6 @@ function update1($dbname)
}
}



//------------Start of install script---------------------------

error_reporting(0); // we want to check system before affraid the user.


/**
* @since 0.84.2
**/
Expand All @@ -509,6 +501,10 @@ function checkConfigFile()
Html::redirect($CFG_GLPI['root_doc'] . "/index.php");
}


//------------Start of install script---------------------------


if (!isset($_SESSION['can_process_install']) || !isset($_POST["install"])) {
$_SESSION = [];

Expand Down
9 changes: 0 additions & 9 deletions phpunit/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,11 @@
* ---------------------------------------------------------------------
*/

use Glpi\Application\ErrorHandler;
use Glpi\Cache\CacheManager;
use Glpi\Cache\SimpleCache;
use Glpi\Kernel\Kernel;
use Symfony\Component\Cache\Adapter\ArrayAdapter;

ini_set('display_errors', 'On'); // Ensure errors happening during test suite bootstrapping are always displayed
error_reporting(E_ALL);

define('GLPI_URI', getenv('GLPI_URI') ?: 'http://localhost:80');
define('GLPI_STRICT_DEPRECATED', true); //enable strict depreciations

Expand Down Expand Up @@ -95,8 +91,3 @@
$tu_oauth_client->getFromDBByCrit(['name' => 'Test OAuth Client']);
define('TU_OAUTH_CLIENT_ID', $tu_oauth_client->fields['identifier']);
define('TU_OAUTH_CLIENT_SECRET', $tu_oauth_client->fields['secret']);

// There is no need to pollute the output with error messages.
ini_set('display_errors', 'Off');
ErrorHandler::getInstance()->disableOutput();
ErrorHandler::getInstance()->setForwardToInternalHandler(false);
13 changes: 0 additions & 13 deletions phpunit/functional/Glpi/Controller/ErrorControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
use Glpi\Exception\Http\HttpException;
use Glpi\Exception\Http\NotFoundHttpException;
use PHPUnit\Framework\Attributes\DataProvider;
use Psr\Log\LogLevel;
use Session;
use Symfony\Component\HttpFoundation\Request;

Expand Down Expand Up @@ -182,10 +181,6 @@ public function testErrorPageRendering(
} else {
$this->assertStringNotContainsString('<pre data-testid="stack-trace">', $content);
}

if ($expected_code >= 500) {
$this->hasPhpLogRecordThatContains('*** Uncaught Exception', LogLevel::CRITICAL);
}
}

#[DataProvider('requestProvider')]
Expand Down Expand Up @@ -226,10 +221,6 @@ public function testErrorBlockRendering(
} else {
$this->assertStringNotContainsString('<pre data-testid="stack-trace">', $content);
}

if ($expected_code >= 500) {
$this->hasPhpLogRecordThatContains('*** Uncaught Exception', LogLevel::CRITICAL);
}
}

#[DataProvider('requestProvider')]
Expand Down Expand Up @@ -278,9 +269,5 @@ public function testErrorJsonRendering(

$this->assertArrayHasKey('trace', $decoded_content);
$this->assertEquals($debug_mode, $decoded_content['trace'] !== null);

if ($expected_code >= 500) {
$this->hasPhpLogRecordThatContains('*** Uncaught Exception', LogLevel::CRITICAL);
}
}
}
Loading

0 comments on commit 576fcd0

Please sign in to comment.