From 50490d51ea8999839e4b3fbde7bda54f206c708e Mon Sep 17 00:00:00 2001 From: Michal Niewrzal Date: Fri, 18 Nov 2016 14:25:05 +0100 Subject: [PATCH] Fix formatting makes LS non-responsive (#153) --- composer.json | 2 +- src/Formatter.php | 31 +++++++++++++++++++++++++------ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/composer.json b/composer.json index f44409e..9c78d3e 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", "netresearch/jsonmapper": "^1.0", "webmozart/path-util": "^2.3", "webmozart/glob": "^4.1", diff --git a/src/Formatter.php b/src/Formatter.php index 37e3f4c..2787cb7 100644 --- a/src/Formatter.php +++ b/src/Formatter.php @@ -3,16 +3,22 @@ declare(strict_types = 1); namespace LanguageServer; -use LanguageServer\Protocol\ { +use LanguageServer\Protocol\{ TextEdit, Range, Position }; -use PHP_CodeSniffer; use Exception; +use PHP_CodeSniffer\{ + Config, + Ruleset +}; +use PHP_CodeSniffer\Files\DummyFile; +use PHP_CodeSniffer\Util\Tokens; abstract class Formatter { + /** * Generate array of TextEdit changes for content formatting. * @@ -24,10 +30,23 @@ abstract class Formatter */ public static function format(string $content, string $uri) { + if (!defined('PHP_CODESNIFFER_CBF')) { + define('PHP_CODESNIFFER_CBF', true); + } + + if (!defined('PHP_CODESNIFFER_VERBOSITY')) { + 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); + + // Autoload class to set up a bunch of PHP_CodeSniffer-specific token type constants + spl_autoload_call(Tokens::class); + + $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 +101,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); } }