Skip to content

Instantly share code, notes, and snippets.

@Cyken-Zeraux
Created November 22, 2016 00:02
Show Gist options
  • Save Cyken-Zeraux/9deca384cb4dd54808192e13d2b1b145 to your computer and use it in GitHub Desktop.
Save Cyken-Zeraux/9deca384cb4dd54808192e13d2b1b145 to your computer and use it in GitHub Desktop.
PHP_Codesniffer V3 Javascript Tokenizer
<?php
namespace MyCustomProject;
use PHP_CodeSniffer\Runner;
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Files\DummyFile;
use PHP_CodeSniffer\Ruleset as Ruleset;
use PHP_CodeSniffer\Util as Util;
// Ensure this option is enabled or else line endings will not always
// be detected properly for files created on a Mac with the /r line ending.
ini_set('auto_detect_line_endings', true);
// Include the PHPCS autoloader, however you need to.
require_once __DIR__.'\vendor\autoload.php';
// Init the PHPCS runner; no settings are required.
$runner = new Runner();
$runner->config = new Config();
// Saves passing the Config object into other objects that only need
// the verbostity flag for deubg output.
if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
define('PHP_CODESNIFFER_VERBOSITY', $runner->config->verbosity);
}
// Create this class so it is autoloaded and sets up a bunch
// of PHP_CodeSniffer-specific token type constants.
$tokens = new Util\Tokens();
// The ruleset contains all the information about how the files
// should be checked and/or fixed.
$runner->ruleset = new Ruleset($runner->config);
// Create a new JS file, but only tokenize it - don't process it.
$fileContent = file_get_contents(__DIR__.'/temp.js');
$file = new DummyFile($fileContent, $runner->ruleset, $runner->config);
$file->tokenizerType = 'JS';
$file->parse();
// Get the tokens of the file. Note that the first token is a T_OPEN_TAG
// token and the last is a T_CLOSE_TAG token, so these can be removed
// to make the token array cleaner because they are only needed
// by PHP_CodeSniffer sniffs.
$tokens = $file->getTokens();
array_pop($tokens);
array_shift($tokens);
file_put_contents('hi.json', json_encode($tokens, JSON_PRETTY_PRINT));
//print_r($tokens);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment