start() public method

Starts the stack traversal and tells listeners when tokens are found.
public start ( string $contents = null ) : void
$contents string The contents to parse. If NULL, the content is taken from the file system.
return void
 /**
  * Initialize & tokenize PHP_CodeSniffer_File with code from this file.
  *
  * Methods used for these tests can be found at the bottom of
  * this file.
  *
  * @return void
  */
 public function setUp()
 {
     $phpcs = new PHP_CodeSniffer();
     $this->_phpcsFile = new PHP_CodeSniffer_File(__FILE__, array(), array(), array(), $phpcs);
     $contents = file_get_contents(__FILE__);
     $this->_phpcsFile->start($contents);
 }
Example #2
0
 public function cswExecute()
 {
     // PHP_CodeSniffer - silent prepare
     ob_start();
     $this->setTokenListeners($this->cswStandard, array());
     $this->populateCustomRules();
     $this->populateTokenListeners();
     $tlisteners = $this->getTokenSniffs();
     ob_end_clean();
     // PHP_CodeSniffer - silent process each item and collect results
     foreach ($this->cswData as $index => $item) {
         ob_start();
         $pcsFile = new PHP_CodeSniffer_File('', $tlisteners['file'], $this->allowedFileExtensions, $this->ruleset, $this);
         $pcsFile->start($item['code']);
         $this->cswData[$index]['output'] = $this->storeOutput ? ob_get_contents() : 'output disabled';
         ob_end_clean();
         // free some memory
         unset($this->cswData[$index]['code']);
         // prepare full report
         $this->cswData[$index]['messages'] = $this->mergeMessages($pcsFile->getErrors(), $pcsFile->getWarnings(), $item['code_lines']);
         // prepare report for lines
         $this->cswData[$index]['report_for_lines'] = $this->createReportForLines($this->cswData[$index]);
     }
     // return data
     return $this->cswData;
 }
 /**
  * Attempt to fix the file by processing it until no fixes are made.
  *
  * @return boolean
  */
 public function fixFile()
 {
     $fixable = $this->_currentFile->getFixableCount();
     if ($fixable === 0) {
         // Nothing to fix.
         return false;
     }
     $this->enabled = true;
     $loops = 0;
     while ($loops < 50) {
         ob_start();
         if ($loops === 0) {
             // First time through, don't reparse the file, saving time.
             $contents = null;
         } else {
             // Only needed once file content has changed.
             $contents = $this->getContents();
             /*
             @ob_end_clean();
             $debugContent = str_replace("\n", "\033[30;1m\\n\n\033[0m", $contents);
             $debugContent = str_replace("\t", "\033[30;1m»\t\033[0m", $debugContent);
             $debugContent = str_replace(' ', "\033[30;1m·\033[0m", $debugContent);
             echo $debugContent;
             */
         }
         $this->_currentFile->refreshTokenListeners();
         $this->_currentFile->start($contents);
         ob_end_clean();
         /*
         Possibly useful as a fail-safe, but may mask problems with the actual
         fixes being performed.
         $newContents = $this->getContents();
         if ($newContents === $contents) {
             break;
         }
         */
         $loops++;
         if ($this->_numFixes === 0) {
             // Nothing left to do.
             break;
         } else {
             if (PHP_CODESNIFFER_VERBOSITY > 1) {
                 echo "\tFixed {$this->_numFixes} violations, starting over" . PHP_EOL;
             }
         }
     }
     //end while
     $this->enabled = false;
     if ($this->_numFixes > 0) {
         if (PHP_CODESNIFFER_VERBOSITY > 1) {
             @ob_end_clean();
             echo "\tReached maximum number of loops with {$this->_numFixes} violations left unfixed" . PHP_EOL;
             ob_start();
         }
         return false;
     }
     return true;
 }
 /**
  * @param \Symfony\Component\Finder\SplFileInfo $fileInfo
  *
  * @return void
  */
 public function addDependencies(SplFileInfo $fileInfo)
 {
     $content = $fileInfo->getContents();
     $_SERVER['argv'] = [];
     if (!defined('STDIN')) {
         define('STDIN', fopen(__FILE__, 'r'));
     }
     $file = new \PHP_CodeSniffer_File($fileInfo->getPathname(), [], [], new \PHP_CodeSniffer());
     $file->start($content);
     $tokens = $file->getTokens();
     $pointer = 0;
     $classNames = [];
     while ($foundPosition = $file->findNext([T_NEW, T_USE, T_DOUBLE_COLON], $pointer)) {
         $pointer = $foundPosition + 1;
         $currentToken = $tokens[$foundPosition];
         if ($currentToken['type'] === 'T_NEW' || $currentToken['type'] === 'T_USE') {
             $pointer = $foundPosition + 2;
             $endOfNew = $file->findNext([T_SEMICOLON, T_OPEN_PARENTHESIS, T_WHITESPACE, T_DOUBLE_COLON], $pointer);
             $classNameParts = array_slice($tokens, $pointer, $endOfNew - $foundPosition - 2);
             $classNames[] = $this->buildClassName($classNameParts);
         }
         if ($currentToken['type'] === 'T_DOUBLE_COLON') {
             $pointer = $foundPosition + 1;
             $startOf = $file->findPrevious([T_OPEN_PARENTHESIS, T_WHITESPACE, T_OPEN_SQUARE_BRACKET], $foundPosition - 1) + 1;
             $classNameParts = array_slice($tokens, $startOf, $foundPosition - $startOf);
             $classNames[] = $this->buildClassName($classNameParts);
         }
     }
     $classNames = array_unique($classNames);
     foreach ($classNames as $className) {
         $className = ltrim($className, '\\');
         if (strpos($className, '_') === false && strpos($className, '\\') === false) {
             continue;
         }
         if (strpos($className, 'Spryker') !== false || strpos($className, 'Generated') !== false || strpos($className, 'Orm') !== false || strpos($className, 'static') !== false || strpos($className, 'self') !== false) {
             continue;
         }
         $dependencyInformation[DependencyTree::META_FOREIGN_LAYER] = 'external';
         $dependencyInformation[DependencyTree::META_FOREIGN_CLASS_NAME] = $className;
         $dependencyInformation[DependencyTree::META_FOREIGN_IS_EXTERNAL] = true;
         $this->addDependency($fileInfo, 'external', $dependencyInformation);
     }
     $this->cleanAutoloader();
 }
 /**
  * Process the sniffs for a single file.
  *
  * Does raw processing only. No interactive support or error checking.
  *
  * @param string $file     The file to process.
  * @param string $contents The contents to parse. If NULL, the content
  *                         is taken from the file system.
  *
  * @return PHP_CodeSniffer_File
  * @see    processFile()
  */
 private function _processFile($file, $contents)
 {
     $stdin = false;
     $cliValues = $this->cli->getCommandLineValues();
     if (empty($cliValues['files']) === true) {
         $stdin = true;
     }
     if (PHP_CODESNIFFER_VERBOSITY > 0 || PHP_CODESNIFFER_CBF === true && $stdin === false) {
         $startTime = microtime(true);
         echo 'Processing ' . basename($file) . ' ';
         if (PHP_CODESNIFFER_VERBOSITY > 1) {
             echo PHP_EOL;
         }
     }
     $phpcsFile = new PHP_CodeSniffer_File($file, $this->_tokenListeners, $this->ruleset, $this);
     $phpcsFile->start($contents);
     if (PHP_CODESNIFFER_VERBOSITY > 0 || PHP_CODESNIFFER_CBF === true && $stdin === false) {
         $timeTaken = (microtime(true) - $startTime) * 1000;
         if ($timeTaken < 1000) {
             $timeTaken = round($timeTaken);
             echo "DONE in {$timeTaken}ms";
         } else {
             $timeTaken = round($timeTaken / 1000, 2);
             echo "DONE in {$timeTaken} secs";
         }
         if (PHP_CODESNIFFER_CBF === true) {
             $errors = $phpcsFile->getFixableCount();
             echo " ({$errors} fixable violations)" . PHP_EOL;
         } else {
             $errors = $phpcsFile->getErrorCount();
             $warnings = $phpcsFile->getWarningCount();
             echo " ({$errors} errors, {$warnings} warnings)" . PHP_EOL;
         }
     }
     return $phpcsFile;
 }
Example #6
0
 /**
  * Process the sniffs for a single file.
  *
  * Does raw processing only. No interactive support or error checking.
  *
  * @param string $file         The file to process.
  * @param string $contents     The contents to parse. If NULL, the content
  *                             is taken from the file system.
  * @param array  $restrictions The sniff codes to restrict the
  *                             violations to.
  *
  * @return PHP_CodeSniffer_File
  * @see    processFile()
  */
 private function _processFile($file, $contents, $restrictions)
 {
     if (PHP_CODESNIFFER_VERBOSITY > 0) {
         $startTime = time();
         echo 'Processing ' . basename($file) . ' ';
         if (PHP_CODESNIFFER_VERBOSITY > 1) {
             echo PHP_EOL;
         }
     }
     $phpcsFile = new PHP_CodeSniffer_File($file, $this->_tokenListeners, $this->allowedFileExtensions, $this->ruleset, $restrictions, $this);
     $phpcsFile->start($contents);
     $phpcsFile->cleanUp();
     if (PHP_CODESNIFFER_VERBOSITY > 0) {
         $timeTaken = time() - $startTime;
         if ($timeTaken === 0) {
             echo 'DONE in < 1 second';
         } else {
             if ($timeTaken === 1) {
                 echo 'DONE in 1 second';
             } else {
                 echo "DONE in {$timeTaken} seconds";
             }
         }
         $errors = $phpcsFile->getErrorCount();
         $warnings = $phpcsFile->getWarningCount();
         echo " ({$errors} errors, {$warnings} warnings)" . PHP_EOL;
     }
     return $phpcsFile;
 }
Example #7
0
 /**
  * Attempt to fix the file by processing it until no fixes are made.
  *
  * @return boolean
  */
 public function fixFile()
 {
     $fixable = $this->_currentFile->getFixableCount();
     if ($fixable === 0) {
         // Nothing to fix.
         return false;
     }
     $stdin = false;
     $cliValues = $this->_currentFile->phpcs->cli->getCommandLineValues();
     if (empty($cliValues['files']) === true) {
         $stdin = true;
     }
     $this->enabled = true;
     $this->_loops = 0;
     while ($this->_loops < 50) {
         ob_start();
         // Only needed once file content has changed.
         $contents = $this->getContents();
         if (PHP_CODESNIFFER_VERBOSITY > 2) {
             @ob_end_clean();
             echo '---START FILE CONTENT---' . PHP_EOL;
             $lines = explode($this->_currentFile->eolChar, $contents);
             $max = strlen(count($lines));
             foreach ($lines as $lineNum => $line) {
                 $lineNum++;
                 echo str_pad($lineNum, $max, ' ', STR_PAD_LEFT) . '|' . $line . PHP_EOL;
             }
             echo '--- END FILE CONTENT ---' . PHP_EOL;
             ob_start();
         }
         $this->_currentFile->refreshTokenListeners();
         $this->_currentFile->start($contents);
         ob_end_clean();
         $this->_loops++;
         if (PHP_CODESNIFFER_CBF === true && $stdin === false) {
             echo "\r" . str_repeat(' ', 80) . "\r";
             echo "\t=> Fixing file: {$this->_numFixes}/{$fixable} violations remaining [made {$this->_loops} pass";
             if ($this->_loops > 1) {
                 echo 'es';
             }
             echo ']... ';
         }
         if ($this->_numFixes === 0) {
             // Nothing left to do.
             break;
         } else {
             if (PHP_CODESNIFFER_VERBOSITY > 1) {
                 echo "\t* fixed {$this->_numFixes} violations, starting loop " . ($this->_loops + 1) . ' *' . PHP_EOL;
             }
         }
     }
     //end while
     $this->enabled = false;
     if ($this->_numFixes > 0) {
         if (PHP_CODESNIFFER_VERBOSITY > 1) {
             @ob_end_clean();
             echo "\t*** Reached maximum number of loops with {$this->_numFixes} violations left unfixed ***" . PHP_EOL;
             ob_start();
         }
         return false;
     }
     return true;
 }
Example #8
0
 /**
  * Attempt to fix the file by processing it until no fixes are made.
  *
  * @return boolean
  */
 public function fixFile()
 {
     $fixable = $this->_currentFile->getFixableCount();
     if ($fixable === 0) {
         // Nothing to fix.
         return false;
     }
     $this->enabled = true;
     $loops = 0;
     while ($loops < 50) {
         ob_start();
         // Only needed once file content has changed.
         $contents = $this->getContents();
         /*
             Useful for debugging fixed contents.
             @ob_end_clean();
             $debugContent = PHP_CodeSniffer::prepareForOutput($contents);
             echo $debugContent;
             ob_start();
         */
         $this->_currentFile->refreshTokenListeners();
         $this->_currentFile->start($contents);
         ob_end_clean();
         /*
             Possibly useful as a fail-safe, but may mask problems with the actual
             fixes being performed.
             $newContents = $this->getContents();
             if ($newContents === $contents) {
                 break;
             }
         */
         $loops++;
         if (PHP_CODESNIFFER_CBF === true) {
             echo "\r" . str_repeat(' ', 80) . "\r";
             echo "\t=> Fixing file: {$this->_numFixes}/{$fixable} violations remaining [made {$loops} pass";
             if ($loops > 1) {
                 echo 'es';
             }
             echo ']... ';
         }
         if ($this->_numFixes === 0) {
             // Nothing left to do.
             break;
         } else {
             if (PHP_CODESNIFFER_VERBOSITY > 1) {
                 echo "\t* fixed {$this->_numFixes} violations, starting loop " . ($loops + 1) . ' *' . PHP_EOL;
             }
         }
     }
     //end while
     $this->enabled = false;
     if ($this->_numFixes > 0) {
         if (PHP_CODESNIFFER_VERBOSITY > 1) {
             @ob_end_clean();
             echo "\t*** Reached maximum number of loops with {$this->_numFixes} violations left unfixed ***" . PHP_EOL;
             ob_start();
         }
         return false;
     }
     return true;
 }
Example #9
0
 /**
  * Run the code sniffs over a signle given file.
  *
  * Processes the file and runs the PHP_CodeSniffer sniffs to verify that it
  * conforms with the standard.
  *
  * @param string $file The file to process.
  *
  * @return void
  * @throws PHP_CodeSniffer_Exception If the file could not be processed.
  */
 private function _processFile($file)
 {
     $file = realpath($file);
     if (file_exists($file) === false) {
         throw new PHP_CodeSniffer_Exception("Source file {$file} does not exist");
     }
     if (PHP_CODESNIFFER_VERBOSITY > 0) {
         $startTime = time();
         echo 'Processing ' . basename($file) . ' ';
         if (PHP_CODESNIFFER_VERBOSITY > 1) {
             echo PHP_EOL;
         }
     }
     $phpcsFile = new PHP_CodeSniffer_File($file, $this->_listeners);
     $this->_files[] = $phpcsFile;
     $phpcsFile->start();
     if (PHP_CODESNIFFER_VERBOSITY > 0) {
         $timeTaken = time() - $startTime;
         if ($timeTaken === 0) {
             echo 'DONE in < 1 second';
         } else {
             if ($timeTaken === 1) {
                 echo 'DONE in 1 second';
             } else {
                 echo "DONE in {$timeTaken} seconds";
             }
         }
         $errors = $phpcsFile->getErrorCount();
         $warnings = $phpcsFile->getWarningCount();
         echo " ({$errors} errors, {$warnings} warnings)" . PHP_EOL;
     }
 }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     // Call realpath() before constructing PHP_CodeSniffer because the
     // constructor changes our current working directory.  An argument handler
     // which sanitized user input would be nice:
     // http://trac.symfony-project.com/ticket/3486
     $arguments['path'] = realpath($arguments['path']);
     $phpcs = new PHP_CodeSniffer();
     $finder = new SvnFinder();
     foreach ($finder->in($arguments['path']) as $path) {
         $config = $this->getConfigForPath($path);
         if (!isset($config['code']['standard']) && !isset($config['preamble']) && !isset($config['props'])) {
             continue;
         }
         // HACK: It is not easy to modify a file's token listeners after it is
         // constructed, so construct a populated file if the code standard is
         // defined, and an empty file otherwise
         if (isset($config['code']['standard'])) {
             // HACK: PHP_CodeSniffer_File now expects an array of
             // PHP_CodeSniffer_Sniff instances, which
             // PHP_CodeSniffer::getTokenListeners() does not return
             $processPhpcs = new PHP_CodeSniffer();
             $processPhpcs->process(array(), $config['code']['standard']);
             $listeners = $processPhpcs->getTokenSniffs();
             $phpcsFile = new PHP_CodeSniffer_File($path, $listeners['file'], $phpcs->allowedFileExtensions);
             $phpcsFile->start();
         } else {
             $phpcsFile = new PHP_CodeSniffer_File($path, array(), $phpcs->allowedFileExtensions);
         }
         if (isset($config['preamble'])) {
         }
         if (isset($config['props'])) {
             $props = $this->getPropsFromPath($path);
             foreach ($props + $config['props'] as $key => $value) {
                 if (isset($props[$key]) && !isset($config['props'][$key])) {
                     $phpcsFile->addError('SVN property "' . $key . '" = "' . $props[$key] . '" found but not expected', 0);
                     continue;
                 }
                 if (!isset($props[$key]) && isset($config['props'][$key])) {
                     $phpcsFile->addError('SVN property "' . $key . '" = "' . $config['props'][$key] . '" expected but not found', 0);
                     continue;
                 }
                 if ($props[$key] != $config['props'][$key]) {
                     $phpcsFile->addError('SVN property "' . $key . '" = "' . $props[$key] . '" expected to match "' . $config['props'][$key] . '"', 0);
                 }
             }
         }
         $phpcs->addFile($phpcsFile);
     }
     $phpcs->printErrorReport();
 }
Example #11
0
 /**
  * Process the sniffs for a single file.
  *
  * Does raw processing only. No interactive support or error checking.
  *
  * @param string $file     The file to process.
  * @param string $contents The contents to parse. If NULL, the content
  *                         is taken from the file system.
  *
  * @return \PHP_CodeSniffer_File
  * @see    processFile()
  * @see    \PHP_CodeSniffer::_processFile()
  */
 protected function startProcessFile($file, $contents)
 {
     //omitted process notification
     $phpcsFile = new \PHP_CodeSniffer_File($file, $this->tokenListeners, $this->ruleset, $this);
     $phpcsFile->start($contents);
     //omitted extra time report
     return $phpcsFile;
 }
 /**
  * Process the sniffs for a single file.
  *
  * Does raw processing only. No interactive support or error checking.
  *
  * @param string $file     The file to process.
  * @param string $contents The contents to parse. If NULL, the content
  *                         is taken from the file system.
  *
  * @return PHP_CodeSniffer_File
  * @see    processFile()
  */
 private function _processFile($file, $contents)
 {
     if (PHP_CODESNIFFER_VERBOSITY > 0) {
         $startTime = microtime(true);
         echo 'Processing ' . basename($file) . ' ';
         if (PHP_CODESNIFFER_VERBOSITY > 1) {
             echo PHP_EOL;
         }
     }
     $phpcsFile = new PHP_CodeSniffer_File($file, $this->_tokenListeners, $this->allowedFileExtensions, $this->ruleset, $this);
     $phpcsFile->start($contents);
     if (PHP_CODESNIFFER_VERBOSITY > 0) {
         $timeTaken = (microtime(true) - $startTime) * 1000;
         if ($timeTaken < 1000) {
             $timeTaken = round($timeTaken);
             echo "DONE in {$timeTaken}ms";
         } else {
             $timeTaken = round($timeTaken / 1000, 2);
             echo "DONE in {$timeTaken} secs";
         }
         $errors = $phpcsFile->getErrorCount();
         $warnings = $phpcsFile->getWarningCount();
         echo " ({$errors} errors, {$warnings} warnings)" . PHP_EOL;
     }
     return $phpcsFile;
 }