From 4b3611d20c9f274bbc93a25bc8f95ac89046246f Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 23 Dec 2018 15:28:48 +0100 Subject: [PATCH] Ruleset/basic validation: improve error messages While the `libxml` error messages are far from perfect, they at least give some clue as to where to look for the error in a ruleset file. This PR changes two things: 1. Previously, a PHP warning would also be thrown for a ruleset of a standard which is not used in the current run. This warning is now silenced. 2. However, for the standards and rulesets actually _used_ by the current run, any potential warnings are made more readable and will now also mention the file in which they were encountered. Previously the output would be along the lines of: ``` Warning: simplexml_load_string(): Entity: line 82: parser error : Opening and ending tag mismatch: rule line 80 and rue in /path/to/PHP_CodeSniffer/src/Util/Standards.php on line 119 Warning: simplexml_load_string(): in /path/to/PHP_CodeSniffer/src/Util/Standards.php on line 119 Warning: simplexml_load_string(): ^ in /path/to/PHP_CodeSniffer/src/Util/Standards.php on line 119 ``` Now, it will look like: ``` ERROR: Ruleset /path/to/ruleset.xml is not valid - On line 82, column 10: Opening and ending tag mismatch: rule line 80 and rue ``` Loosely related to #2188 --- src/Ruleset.php | 14 ++++++++++++-- src/Util/Standards.php | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/Ruleset.php b/src/Ruleset.php index a50dde2a95..b20618686c 100644 --- a/src/Ruleset.php +++ b/src/Ruleset.php @@ -315,11 +315,21 @@ public function processRuleset($rulesetPath, $depth=0) echo 'Processing ruleset '.Util\Common::stripBasepath($rulesetPath, $this->config->basepath).PHP_EOL; } - $ruleset = @simplexml_load_string(file_get_contents($rulesetPath)); + libxml_use_internal_errors(true); + $ruleset = simplexml_load_string(file_get_contents($rulesetPath)); if ($ruleset === false) { - throw new RuntimeException("Ruleset $rulesetPath is not valid"); + $errorMsg = "Ruleset $rulesetPath is not valid".PHP_EOL; + $errors = libxml_get_errors(); + foreach ($errors as $error) { + $errorMsg .= '- On line '.$error->line.', column '.$error->column.': '.$error->message; + } + + libxml_clear_errors(); + throw new RuntimeException($errorMsg); } + libxml_use_internal_errors(false); + $ownSniffs = []; $includedSniffs = []; $excludedSniffs = []; diff --git a/src/Util/Standards.php b/src/Util/Standards.php index e38d0b327e..a5436c2594 100644 --- a/src/Util/Standards.php +++ b/src/Util/Standards.php @@ -116,7 +116,7 @@ public static function getInstalledStandardDetails( $installedStandards = []; foreach ($rulesets as $rulesetPath) { - $ruleset = simplexml_load_string(file_get_contents($rulesetPath)); + $ruleset = @simplexml_load_string(file_get_contents($rulesetPath)); if ($ruleset === false) { continue; }