From eae1c8a181fbaf926054e442a2da33d5ee90412a Mon Sep 17 00:00:00 2001 From: Michal Niewrzal Date: Thu, 17 Nov 2016 12:53:52 +0100 Subject: [PATCH] Formatting makes LS non-responsive #144 --- composer.json | 2 +- src/Formatter.php | 30 +++++++++++++++++++++++++----- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/composer.json b/composer.json index 2afb468..da8cabf 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ "phpdocumentor/reflection-docblock": "^3.0", "sabre/event": "^5.0", "felixfbecker/advanced-json-rpc": "^2.0", - "squizlabs/php_codesniffer" : "^2.7", + "squizlabs/php_codesniffer" : "3.0.0RC1", "symfony/debug": "^3.1", "netresearch/jsonmapper": "^1.0", "webmozart/path-util": "^2.3", diff --git a/src/Formatter.php b/src/Formatter.php index 37e3f4c..c0c0395 100644 --- a/src/Formatter.php +++ b/src/Formatter.php @@ -8,11 +8,17 @@ use LanguageServer\Protocol\ { Range, Position }; -use PHP_CodeSniffer; use Exception; +use PHP_CodeSniffer\ { + Config, + Ruleset, + Files\DummyFile, + Util\Tokens +}; abstract class Formatter { + /** * Generate array of TextEdit changes for content formatting. * @@ -24,10 +30,24 @@ abstract class Formatter */ public static function format(string $content, string $uri) { + if (defined('PHP_CODESNIFFER_CBF') === false) { + define('PHP_CODESNIFFER_CBF', true); + } + + if (defined('PHP_CODESNIFFER_VERBOSITY') === false) { + define('PHP_CODESNIFFER_VERBOSITY', false); + } + $path = uriToPath($uri); - $cs = new PHP_CodeSniffer(); - $cs->initStandard(self::findConfiguration($path)); - $file = $cs->processFile(null, $content); + $config = new Config(['dummy'], false); + $config->standards = self::findConfiguration($path); + + // Create this class so it is autoloaded and sets up a bunch + // of PHP_CodeSniffer-specific token type constants. + new Tokens(); + + $file = new DummyFile($content, new Ruleset($config), $config); + $file->process(); $fixed = $file->fixer->fixFile(); if (!$fixed && $file->getErrorCount() > 0) { throw new Exception('Unable to format file'); @@ -82,7 +102,7 @@ abstract class Formatter $currentDir = dirname($currentDir); } while ($currentDir !== '.' && $currentDir !== $lastDir); - $standard = PHP_CodeSniffer::getConfigData('default_standard') ?? 'PSR2'; + $standard = Config::getConfigData('default_standard') ?? 'PSR2'; return explode(',', $standard); } }