getFilename() public method

Returns the absolute filename of this file.
public getFilename ( ) : string
return string
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param  PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param  integer              $stackPtr  The position of the current token in the
  *                                         stack passed in $tokens.
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $tokens = $phpcsFile->getTokens();
     $decName = $phpcsFile->findNext(T_STRING, $stackPtr);
     $fileName = dirname($phpcsFile->getFilename());
     $GnPosition = strrpos($fileName, DIRECTORY_SEPARATOR . 'GN');
     if (false === $GnPosition) {
         return;
     }
     $fileName = substr($fileName, $GnPosition + 1);
     $fileName .= DIRECTORY_SEPARATOR . basename($phpcsFile->getFilename());
     $fileName = substr($fileName, 0, strrpos($fileName, '.'));
     $className = $fileName;
     $className = substr($className, strpos($className, '_'));
     $className = substr($className, strpos($className, DIRECTORY_SEPARATOR) + 1);
     $fileName = str_replace(DIRECTORY_SEPARATOR, '_', $fileName);
     $className = str_replace(DIRECTORY_SEPARATOR, '_', $className);
     if (strpos($fileName, '__') === false) {
         $className = $fileName;
     }
     if ($tokens[$decName]['content'] !== $fileName and $tokens[$decName]['content'] !== $className) {
         $name = ucfirst($tokens[$stackPtr]['content']);
         $file .= '"' . $tokens[$stackPtr]['content'] . ' ' . $className . '".';
         $phpcsFile->addEvent('MATCH_CLASS_NAME', array('name' => $name, 'file' => $file), $stackPtr);
     }
 }
Example #2
0
 /**
  * Determines the info file a file might be associated with.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  *
  * @return string|false The project info file name or false if it could not
  *   be derived.
  */
 public static function getInfoFile(PHP_CodeSniffer_File $phpcsFile)
 {
     // Cache the project name per file as this might get called often.
     static $cache;
     if (isset($cache[$phpcsFile->getFilename()]) === true) {
         return $cache[$phpcsFile->getFilename()];
     }
     $pathParts = pathinfo($phpcsFile->getFilename());
     // Search for an info file.
     $dir = $pathParts['dirname'];
     do {
         $infoFiles = glob("{$dir}/*.info.yml");
         if (empty($infoFiles) === true) {
             $infoFiles = glob("{$dir}/*.info");
         }
         // Go one directory up if we do not find an info file here.
         $dir = dirname($dir);
     } while (empty($infoFiles) && $dir != dirname($dir));
     // No info file found, so we give up.
     if (empty($infoFiles) === true) {
         $cache[$phpcsFile->getFilename()] = false;
         return false;
     }
     // Sort the info file names and take the shortest info file.
     usort($infoFiles, array('DrupalPractice_Project', 'compareLength'));
     $infoFile = $infoFiles[0];
     $cache[$phpcsFile->getFilename()] = $infoFile;
     return $infoFile;
 }
Example #3
0
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param int                  $stackPtr  The position of the current token
  *                                        in the stack passed in $tokens.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     // We want to run this method only once per file, so we remember if this has
     // been called already.
     static $called = array();
     if (isset($called[$phpcsFile->getFilename()]) === false) {
         $called[$phpcsFile->getFilename()] = true;
         // Retrieve the raw file content, as the tokens do not work consistently
         // for different file types (CSS and javascript files have additional
         // artifical tokens at the end for example).
         $filename = $phpcsFile->getFilename();
         // file_get_contents requires a file path, but some programs will pass
         // in info via STDIN. Change the filename to something file_get_contents
         // will understand.
         if ($filename == 'STDIN') {
             $filename = 'php://stdin';
         }
         $content = file_get_contents($filename);
         $error = false;
         $lastChar = substr($content, -1);
         // There must be a \n character at the end of the last token.
         if ($lastChar !== $phpcsFile->eolChar) {
             $error = true;
         } else {
             if (substr($content, -2, 1) === $phpcsFile->eolChar) {
                 $error = true;
             }
         }
         if ($error === true) {
             $error = 'Files must end in a single new line character';
             $phpcsFile->addError($error, $phpcsFile->numTokens - 1, 'FileEnd');
         }
     }
     //end if
 }
 /**
  * Processes php files and looks for MOODLE_INTERNAL or config.php
  * inclusion.
  *
  * @param PHP_CodeSniffer_File $file The file being scanned.
  * @param int $pointer The position in the stack.
  */
 public function process(PHP_CodeSniffer_File $file, $pointer)
 {
     // Special dispensation for behat files.
     if (basename(dirname($file->getFilename())) === 'behat') {
         return;
     }
     // Special dispensation for lang files.
     if (basename(dirname(dirname($file->getFilename()))) === 'lang') {
         return;
     }
     // We only want to do this once per file.
     $prevopentag = $file->findPrevious(T_OPEN_TAG, $pointer - 1);
     if ($prevopentag !== false) {
         return;
     }
     // Find where real code is and check from there.
     $pointer = $this->get_position_of_relevant_code($file, $pointer);
     // OK, we've got to the first bit of relevant code.
     if ($this->is_moodle_internal_or_die_check($file, $pointer)) {
         // There is a MOODLE_INTERNAL check. This file is good, hurrah!
         return;
     }
     if ($this->is_config_php_incluson($file, $pointer)) {
         // We are requiring config.php. This file is good, hurrah!
         return;
     }
     if ($this->is_if_not_moodle_internal_die_check($file, $pointer)) {
         // It's an old-skool MOODLE_INTERNAL check. This file is good, hurrah!
         return;
     }
     // Got here because, so something is not right.
     $file->addWarning('Expected MOODLE_INTERNAL check or config.php inclusion', $pointer);
 }
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param  PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param  integer              $stackPtr  The position of the current token in the
  *                                         stack passed in $tokens.
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $tokens = $phpcsFile->getTokens();
     $decName = $phpcsFile->findNext(T_STRING, $stackPtr);
     $fileName = dirname($phpcsFile->getFilename());
     $GnPosition = strrpos($fileName, DIRECTORY_SEPARATOR . 'GN');
     if (false === $GnPosition) {
         return;
     }
     $fileName = substr($fileName, $GnPosition + 1);
     $fileName .= DIRECTORY_SEPARATOR . basename($phpcsFile->getFilename());
     $fileName = substr($fileName, 0, strrpos($fileName, '.'));
     $className = $fileName;
     $className = substr($className, strpos($className, '_'));
     $className = substr($className, strpos($className, DIRECTORY_SEPARATOR) + 1);
     $fileName = str_replace(DIRECTORY_SEPARATOR, '_', $fileName);
     $className = str_replace(DIRECTORY_SEPARATOR, '_', $className);
     if (strpos($fileName, '__') === false) {
         $className = $fileName;
     }
     if ($tokens[$decName]['content'] !== $fileName and $tokens[$decName]['content'] !== $className) {
         $name = ucfirst($tokens[$stackPtr]['content']);
         $file .= '"' . $tokens[$stackPtr]['content'] . ' ' . $className . '".';
         $error = "La classe (ou interface) {$name} ne doit pas être different du nom de fichier source {$file}" . $phpcsFile->addError($error, $stackPtr, 'FilenameMatchClassname');
     }
 }
 /**
  * Process this function definition.
  *
  * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
  * @param int                  $stackPtr    The position of the function name in the stack.
  *                                           name in the stack.
  * @param int                  $functionPtr The position of the function keyword in the stack.
  *                                           keyword in the stack.
  *
  * @return void
  */
 public function processFunction(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $functionPtr)
 {
     $fileExtension = strtolower(substr($phpcsFile->getFilename(), -7));
     // Only check in *.install files.
     if ($fileExtension !== 'install') {
         return;
     }
     $fileName = substr(basename($phpcsFile->getFilename()), 0, -8);
     $tokens = $phpcsFile->getTokens();
     if ($tokens[$stackPtr]['content'] !== $fileName . '_install' && $tokens[$stackPtr]['content'] !== $fileName . '_requirements') {
         return;
     }
     // This check only applies to Drupal 7, not Drupal 8.
     if (DrupalPractice_Project::getCoreVersion($phpcsFile) !== '7.x') {
         return;
     }
     // Search in the function body for t() calls.
     $string = $phpcsFile->findNext(T_STRING, $tokens[$functionPtr]['scope_opener'], $tokens[$functionPtr]['scope_closer']);
     while ($string !== false) {
         if ($tokens[$string]['content'] === 't' || $tokens[$string]['content'] === 'st') {
             $opener = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $string + 1, null, true);
             if ($opener !== false && $tokens[$opener]['code'] === T_OPEN_PARENTHESIS) {
                 $error = 'Do not use t() or st() in installation phase hooks, use $t = get_t() to retrieve the appropriate localization function name';
                 $phpcsFile->addError($error, $string, 'TranslationFound');
             }
         }
         $string = $phpcsFile->findNext(T_STRING, $string + 1, $tokens[$functionPtr]['scope_closer']);
     }
     //end while
 }
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param integer $stackPtr The position of the current token in the stack passed in $tokens.
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     if (isset($this->_processed[$phpcsFile->getFilename()])) {
         return;
     }
     $filename = $phpcsFile->getFilename();
     $this->_uses = array();
     $next = $stackPtr;
     while ($next !== false) {
         $this->_checkUseToken($phpcsFile, $next);
         $next = $phpcsFile->findNext(T_USE, $next + 1);
     }
     // Prevent multiple uses in the same file from entering
     $this->_processed[$phpcsFile->getFilename()] = true;
     foreach ($this->_uses as $scope => $used) {
         $defined = $sorted = array_keys($used);
         natcasesort($sorted);
         $sorted = array_values($sorted);
         if ($sorted === $defined) {
             continue;
         }
         foreach ($defined as $i => $name) {
             if ($name !== $sorted[$i]) {
                 $error = 'Use classes must be in alphabetical order.';
                 $phpcsFile->addError($error, $used[$name], 'UseInAlphabeticalOrder', array());
             }
         }
     }
 }
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param int                  $stackPtr  The position of the current token
  *                                        in the stack passed in $tokens.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     // If short open tags are off, then any short open tags will be converted
     // to inline_html tags so we can just ignore them.
     // If its on, then we want to ban the use of them.
     $option = ini_get('short_open_tag');
     // Ini_get returns a string "0" if short open tags is off.
     if ($option === '0') {
         return;
     }
     if (!isset($this->files_cache[$phpcsFile->getFilename()]) && !$phpcsFile->findNext(T_OPEN_TAG, $stackPtr + 1) && !$phpcsFile->findNext(T_OPEN_TAG_WITH_ECHO, $stackPtr + 1) && $phpcsFile->findNext(T_CLOSE_TAG, $stackPtr)) {
         $error = 'Файл имеет только один открывающий PHP-тэг, но имеет закрывающий PHP-тэг.';
         $phpcsFile->addError($this->getReqPrefix('REQ.PHP.2.1.1') . $error, $stackPtr);
     }
     $this->files_cache[$phpcsFile->getFilename()] = true;
     $tokens = $phpcsFile->getTokens();
     $openTag = $tokens[$stackPtr];
     if ($openTag['content'] === '<?') {
         $error = 'Short PHP opening tag used. Found "' . $openTag['content'] . '" Expected "<?php".';
         $phpcsFile->addError($this->getReqPrefix('REQ.PHP.2.1.2') . $error, $stackPtr);
     }
     if ($openTag['code'] === T_OPEN_TAG_WITH_ECHO) {
         $nextVar = $tokens[$phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true)];
         $error = 'Short PHP opening tag used with echo. Found "';
         $error .= $openTag['content'] . ' ' . $nextVar['content'] . ' ..." but expected "<?php echo ' . $nextVar['content'] . ' ...".';
         $phpcsFile->addError($this->getReqPrefix('REQ.PHP.2.1.2') . $error, $stackPtr);
     }
 }
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param integer $stackPtr The position of the current token in the stack passed in $tokens.
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     if (isset($this->_processed[$phpcsFile->getFilename()])) {
         return;
     }
     $tokens = $phpcsFile->getTokens();
     $isClosure = $phpcsFile->findPrevious(array(T_CLOSURE), $stackPtr - 1, null, false, null, true);
     if ($isClosure) {
         return;
     }
     // Only one USE declaration allowed per statement.
     $next = $phpcsFile->findNext(array(T_COMMA, T_SEMICOLON), $stackPtr + 1);
     if ($tokens[$next]['code'] === T_COMMA) {
         $error = 'There must be one USE keyword per declaration';
         $phpcsFile->addError($error, $stackPtr, 'MultipleDeclarations');
     }
     $uses = array();
     $next = $stackPtr;
     while (true) {
         $content = '';
         $end = $phpcsFile->findNext(array(T_SEMICOLON, T_OPEN_CURLY_BRACKET), $next);
         $useTokens = array_slice($tokens, $next, $end - $next, true);
         foreach ($useTokens as $index => $token) {
             if ($token['code'] === T_STRING || $token['code'] === T_NS_SEPARATOR) {
                 $content .= $token['content'];
             }
         }
         // Check for class scoping on use. Traits should be
         // ordered independently.
         $scope = 0;
         if (!empty($token['conditions'])) {
             $scope = key($token['conditions']);
         }
         $uses[$scope][$content] = $index;
         $next = $phpcsFile->findNext(T_USE, $end);
         if (!$next) {
             break;
         }
     }
     // Prevent multiple uses in the same file from entering
     $this->_processed[$phpcsFile->getFilename()] = true;
     $ordered = TRUE;
     foreach ($uses as $scope => $used) {
         $defined = $sorted = array_keys($used);
         natcasesort($sorted);
         $sorted = array_values($sorted);
         if ($sorted === $defined) {
             continue;
         }
         foreach ($defined as $i => $name) {
             if ($name !== $sorted[$i]) {
                 $ordered = FALSE;
             }
         }
     }
     if (!$ordered) {
         $error = 'Usings must be in alphabetical order';
         $phpcsFile->addError($error, $stackPtr, 'UseInAlphabeticalOrder', array());
     }
 }
 /**
  * Process this function definition.
  *
  * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
  * @param int                  $stackPtr    The position of the function name in the stack.
  *                                           name in the stack.
  * @param int                  $functionPtr The position of the function keyword in the stack.
  *                                           keyword in the stack.
  *
  * @return void
  */
 public function processFunction(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $functionPtr)
 {
     $fileExtension = strtolower(substr($phpcsFile->getFilename(), -6));
     // Only check in *.module files.
     if ($fileExtension !== 'module') {
         return;
     }
     $fileName = substr(basename($phpcsFile->getFilename()), 0, -7);
     $tokens = $phpcsFile->getTokens();
     if ($tokens[$stackPtr]['content'] !== $fileName . '_menu') {
         return;
     }
     // Search in the function body for t() calls.
     $string = $phpcsFile->findNext(T_STRING, $tokens[$functionPtr]['scope_opener'], $tokens[$functionPtr]['scope_closer']);
     while ($string !== false) {
         if ($tokens[$string]['content'] === 't') {
             $opener = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $string + 1, null, true);
             if ($opener !== false && $tokens[$opener]['code'] === T_OPEN_PARENTHESIS) {
                 $error = 'Do not use t() in hook_menu()';
                 $phpcsFile->addError($error, $string, 'TFound');
             }
         }
         $string = $phpcsFile->findNext(T_STRING, $string + 1, $tokens[$functionPtr]['scope_closer']);
     }
     //end while
 }
Example #11
0
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     if (false !== strpos($phpcsFile->getFilename(), 'model') || false !== strpos($phpcsFile->getFilename(), 'form') || false !== strpos($phpcsFile->getFilename(), 'filter')) {
         return null;
     }
     $tokens = $phpcsFile->getTokens();
     $className = $phpcsFile->findNext(T_STRING, $stackPtr);
     $name = trim($tokens[$className]['content']);
     // "op" prefix
     if (0 !== strpos($name, 'op')) {
         $error = ucfirst($tokens[$stackPtr]['content']) . ' name must begin with "op" prefix';
         $phpcsFile->addError($error, $stackPtr);
     }
     // "Interface" suffix
     if ($tokens[$stackPtr]['code'] === T_INTERFACE && !preg_match('/Interface$/', $name)) {
         $error = ucfirst($tokens[$stackPtr]['content']) . ' name must end with "Interface"';
         $phpcsFile->addError($error, $stackPtr);
     }
     // stripped prefix
     if (0 === strpos($name, 'op')) {
         $name = substr($name, 2);
     }
     if (!PHP_CodeSniffer::isCamelCaps($name, true, true, false)) {
         $error = ucfirst($tokens[$stackPtr]['content']) . ' name is not in camel caps format';
         $phpcsFile->addError($error, $stackPtr);
     }
 }
Example #12
0
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param int                  $stackPtr  The position of the current token in the
  *                                        stack passed in $tokens.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     // Only run this sniff once per info file.
     $end = count($phpcsFile->getTokens()) + 1;
     $fileExtension = strtolower(substr($phpcsFile->getFilename(), -4));
     if ($fileExtension !== 'info') {
         return $end;
     }
     $tokens = $phpcsFile->getTokens();
     $contents = file_get_contents($phpcsFile->getFilename());
     $info = Drupal_Sniffs_InfoFiles_ClassFilesSniff::drupalParseInfoFormat($contents);
     if (isset($info['name']) === false) {
         $error = '"name" property is missing in the info file';
         $phpcsFile->addError($error, $stackPtr, 'Name');
     }
     if (isset($info['description']) === false) {
         $error = '"description" property is missing in the info file';
         $phpcsFile->addError($error, $stackPtr, 'Description');
     }
     if (isset($info['core']) === false) {
         $error = '"core" property is missing in the info file';
         $phpcsFile->addError($error, $stackPtr, 'Core');
     } else {
         if ($info['core'] === '7.x' && isset($info['php']) === true && $info['php'] <= '5.2') {
             $error = 'Drupal 7 core already requires PHP 5.2';
             $ptr = Drupal_Sniffs_InfoFiles_ClassFilesSniff::getPtr('php', $info['php'], $phpcsFile);
             $phpcsFile->addError($error, $ptr, 'D7PHPVersion');
         }
     }
     return $end;
 }
 /**
  * Processes this sniff, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param int                  $stackPtr  The position of the current token in
  *                                        the stack passed in $tokens.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     if (in_array($phpcsFile->getFilename(), $this->visitedFiles)) {
         return;
     }
     $encoding = mb_detect_encoding(file_get_contents($phpcsFile->getFilename()), 'UTF-8, ASCII, ISO-8859-1', true);
     if ($encoding !== 'UTF-8') {
         $error = 'Files must use UTF-8 character set; but ' . $encoding . ' found.';
         $phpcsFile->addError($error, $stackPtr);
     }
 }
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile All the tokens found in the document.
  * @param int                  $stackPtr  The position of the current token in
  *                                        the stack passed in $tokens.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     if ($this->currentFile !== $phpcsFile->getFilename()) {
         $this->classCount = 0;
         $this->currentFile = $phpcsFile->getFilename();
     }
     $this->classCount++;
     if ($this->classCount > 1) {
         $phpcsFile->addError('Multiple classes defined in a single file', $stackPtr);
     }
     return;
 }
Example #15
0
 /**
  * Process this function definition.
  *
  * @param PHP_CodeSniffer_File $phpcsFile    The file being scanned.
  * @param int                  $stackPtr     The position of the function
  *                                           name in the stack.
  * @param int                  $functionPtr  The position of the function
  *                                           keyword in the stack.
  *
  * @return void
  */
 public function processFunction(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $functionPtr)
 {
     $fileExtension = strtolower(substr($phpcsFile->getFilename(), -6));
     // Only check in *.module files.
     if ($fileExtension !== 'module') {
         return;
     }
     $tokens = $phpcsFile->getTokens();
     $fileName = substr(basename($phpcsFile->getFilename()), 0, -7);
     if ($tokens[$stackPtr]['content'] === $fileName . '_install' || $tokens[$stackPtr]['content'] === $fileName . '_uninstall' || $tokens[$stackPtr]['content'] === $fileName . '_requirements' || $tokens[$stackPtr]['content'] === $fileName . '_schema' || $tokens[$stackPtr]['content'] === $fileName . '_enable' || $tokens[$stackPtr]['content'] === $fileName . '_disable') {
         $error = '%s() is an installation hook and must be declared in an install file';
         $data = array($tokens[$stackPtr]['content']);
         $phpcsFile->addError($error, $stackPtr, 'InstallHook', $data);
     }
 }
 /**
  * @param \PHP_CodeSniffer_File $phpCsFile
  * @param int $stackPointer
  *
  * @return void
  */
 protected function addFixableMissingDocBlock(\PHP_CodeSniffer_File $phpCsFile, $stackPointer)
 {
     $fix = $phpCsFile->addFixableError(basename($phpCsFile->getFilename()) . ' has no File Doc Block.', $stackPointer);
     if ($fix) {
         $this->addFileDocBlock($phpCsFile, 0);
     }
 }
 /**
  * Processes the tokens that this sniff is interested in.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
  * @param int                  $stackPtr  The position in the stack where
  *                                        the token was found.
  *
  * @return void
  * @throws PHP_CodeSniffer_Exception If jshint.js could not be run
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $fileName = $phpcsFile->getFilename();
     $rhinoPath = PHP_CodeSniffer::getConfigData('rhino_path');
     $jshintPath = PHP_CodeSniffer::getConfigData('jshint_path');
     if ($rhinoPath === null || $jshintPath === null) {
         return;
     }
     $cmd = "{$rhinoPath} \"{$jshintPath}\" \"{$fileName}\"";
     $msg = exec($cmd, $output, $retval);
     if (is_array($output) === true) {
         foreach ($output as $finding) {
             $matches = array();
             $numMatches = preg_match('/^(.+)\\(.+:([0-9]+).*:[0-9]+\\)$/', $finding, $matches);
             if ($numMatches === 0) {
                 continue;
             }
             $line = (int) $matches[2];
             $message = 'jshint says: ' . trim($matches[1]);
             $phpcsFile->addWarningOnLine($message, $line, 'ExternalTool');
         }
     }
     // Ignore the rest of the file.
     return $phpcsFile->numTokens + 1;
 }
 /**
  * Processes the tokens that this sniff is interested in.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
  * @param int                  $stackPtr  The position in the stack where
  *                                        the token was found.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $fileName = $phpcsFile->getFilename();
     $jslPath = PHP_CodeSniffer::getConfigData('jsl_path');
     if (is_null($jslPath) === true) {
         return;
     }
     $cmd = '"' . $jslPath . '" -nologo -nofilelisting -nocontext -nosummary -output-format __LINE__:__ERROR__ -process "' . $fileName . '"';
     $msg = exec($cmd, $output, $retval);
     // Variable $exitCode is the last line of $output if no error occurs, on
     // error it is numeric. Try to handle various error conditions and
     // provide useful error reporting.
     if ($retval === 2 || $retval === 4) {
         if (is_array($output) === true) {
             $msg = join('\\n', $output);
         }
         throw new PHP_CodeSniffer_Exception("Failed invoking JavaScript Lint, retval was [{$retval}], output was [{$msg}]");
     }
     if (is_array($output) === true) {
         foreach ($output as $finding) {
             $split = strpos($finding, ':');
             $line = substr($finding, 0, $split);
             $message = substr($finding, $split + 1);
             $phpcsFile->addWarningOnLine(trim($message), $line, 'ExternalTool');
         }
     }
     // Ignore the rest of the file.
     return $phpcsFile->numTokens + 1;
 }
 /**
  * Processes normal variables.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file where this token was found.
  * @param int $stackPtr The position where the token was found.
  *
  * @return void
  */
 protected function processVariable(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $tokens = $phpcsFile->getTokens();
     $variableName = $tokens[$stackPtr]['content'];
     $scopeIdentifier = $phpcsFile->getFilename() . $variableName;
     $level = $tokens[$stackPtr]['level'];
     $functionIndex = $phpcsFile->findPrevious(T_FUNCTION, $stackPtr);
     $lastScopeOpen = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$scopeOpeners, $stackPtr);
     //Inline scope openers do not increment the level value
     $scopeOpenDistance = $tokens[$stackPtr]['line'] - $tokens[$lastScopeOpen]['line'];
     if (in_array($tokens[$lastScopeOpen]['code'], PHP_CodeSniffer_Tokens::$scopeOpeners) === true && ($scopeOpenDistance === 1 || $scopeOpenDistance === 0) && $tokens[$stackPtr]['level'] === $tokens[$lastScopeOpen]['level']) {
         ++$level;
     }
     if ($functionIndex !== false && array_key_exists('scope_closer', $tokens[$functionIndex]) && $tokens[$functionIndex]['scope_closer'] > $stackPtr) {
         //Member variables are always ok
         if ($variableName === '$this') {
             return;
         }
         // find previous non-whitespace token. if it's a double colon, assume static class var
         $objOperator = $phpcsFile->findPrevious([T_WHITESPACE], $stackPtr - 1, null, true);
         if ($tokens[$objOperator]['code'] === T_DOUBLE_COLON) {
             return;
         }
         $scopeIdentifier .= $tokens[$functionIndex]['scope_condition'];
     }
     //If this is the first time we've seen this variable in this file/function store the scope depth.
     if (array_key_exists($scopeIdentifier, $this->_variableScopes) === false) {
         $this->_variableScopes[$scopeIdentifier] = $level;
     } elseif ($this->_variableScopes[$scopeIdentifier] > $level) {
         //Verify that the variables we've seen are not appearing in higher scopes.
         $phpcsFile->addWarning("Variable '{$variableName}' is in the wrong scope.", $stackPtr, 'Found');
     }
 }
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     if (strpos($phpcsFile->getFilename(), '/protected/migrations/') !== false) {
         return;
     }
     return parent::process($phpcsFile, $stackPtr);
 }
 /**
  * @param \PHP_CodeSniffer_File $phpCsFile
  * @param int $stackPointer
  *
  * @return void
  */
 protected function addFixableExistingDocBlock(\PHP_CodeSniffer_File $phpCsFile, $stackPointer)
 {
     $fix = $phpCsFile->addFixableError(basename($phpCsFile->getFilename()) . ' has the wrong file doc block', $stackPointer);
     if ($fix) {
         $this->addFileDocBlock($phpCsFile, 0);
     }
 }
Example #22
0
 /**
  * Processes the tokens that this sniff is interested in.
  */
 public function process(PHP_CodeSniffer_File $phpcs_file, $stack_ptr)
 {
     $file_name = $phpcs_file->getFilename();
     $jscs_path = PHP_CodeSniffer::getConfigData('jscs_path');
     if ($jscs_path === NULL) {
         return;
     }
     // JSCS options to generate an output that can be parsed by the script
     // below.
     // @see http://jscs.info/overview.
     $jscs_options = '--reporter=text';
     $cmd = '"' . $jscs_path . '/jscs' . '"' . ' ' . '"' . $file_name . '"' . ' ' . $jscs_options;
     exec($cmd, $output, $retval);
     if (is_array($output) === TRUE) {
         $tokens = $phpcs_file->getTokens();
         $messages = $this->parseMessages($output);
         foreach ($messages as $output) {
             $line_number = $this->parseLineNumber($output);
             $message = $this->parseMessage($output);
             // Find the token at the start of the line.
             $line_token = NULL;
             foreach ($tokens as $ptr => $info) {
                 if ($line_number == $info['line']) {
                     $line_token = $ptr;
                     break;
                 }
             }
             $phpcs_file->addWarning($message, $line_token, 'ExternalTool');
         }
     }
 }
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param int                  $stackPtr  The position of the current token
  *                                        in the stack passed in $tokens.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $tokens = $phpcsFile->getTokens();
     $namespace = '';
     $stackPtr = $phpcsFile->findNext(array(T_CLASS, T_INTERFACE, T_NAMESPACE), 0);
     while ($stackPtr !== false) {
         // Keep track of what namespace we are in.
         if ($tokens[$stackPtr]['code'] === T_NAMESPACE) {
             $nsEnd = $phpcsFile->findNext(array(T_NS_SEPARATOR, T_STRING, T_WHITESPACE), $stackPtr + 1, null, true);
             $namespace = trim($phpcsFile->getTokensAsString($stackPtr + 1, $nsEnd - $stackPtr - 1));
             $stackPtr = $nsEnd;
         } else {
             $nameToken = $phpcsFile->findNext(T_STRING, $stackPtr);
             $name = $tokens[$nameToken]['content'];
             if ($namespace !== '') {
                 $name = $namespace . '\\' . $name;
             }
             $compareName = strtolower($name);
             if (isset($this->foundClasses[$compareName]) === true) {
                 $type = strtolower($tokens[$stackPtr]['content']);
                 $file = $this->foundClasses[$compareName]['file'];
                 $line = $this->foundClasses[$compareName]['line'];
                 $error = 'Duplicate %s name "%s" found; first defined in %s on line %s';
                 $data = array($type, $name, $file, $line);
                 $phpcsFile->addWarning($error, $stackPtr, 'Found', $data);
             } else {
                 $this->foundClasses[$compareName] = array('file' => $phpcsFile->getFilename(), 'line' => $tokens[$stackPtr]['line']);
             }
         }
         $stackPtr = $phpcsFile->findNext(array(T_CLASS, T_INTERFACE, T_NAMESPACE), $stackPtr + 1);
     }
     //end while
 }
Example #24
0
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param int                  $stackPtr  The position of the current token in
  *                                        the stack passed in $tokens.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     if ($this->_phpPath === null) {
         $this->_phpPath = PHP_CodeSniffer::getConfigData('php_path');
         if ($this->_phpPath === null) {
             // PHP_BINARY is available in PHP 5.4+.
             if (defined('PHP_BINARY') === true) {
                 $this->_phpPath = PHP_BINARY;
             } else {
                 return;
             }
         }
     }
     $fileName = $phpcsFile->getFilename();
     $cmd = $this->_phpPath . " -l \"{$fileName}\" 2>&1";
     $output = shell_exec($cmd);
     $matches = array();
     if (preg_match('/^.*error:(.*) in .* on line ([0-9]+)/', trim($output), $matches) === 1) {
         $error = trim($matches[1]);
         $line = (int) $matches[2];
         $phpcsFile->addErrorOnLine("PHP syntax error: {$error}", $line, 'PHPSyntax');
     }
     // Ignore the rest of the file.
     return $phpcsFile->numTokens + 1;
 }
 /**
  * Process this function definition.
  *
  * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
  * @param int                  $stackPtr    The position of the function name in the stack.
  *                                           name in the stack.
  * @param int                  $functionPtr The position of the function keyword in the stack.
  *                                           keyword in the stack.
  *
  * @return void
  */
 public function processFunction(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $functionPtr)
 {
     $fileExtension = strtolower(substr($phpcsFile->getFilename(), -6));
     // Only check in *.module files.
     if ($fileExtension !== 'module') {
         return;
     }
     // This check only applies to Drupal 7, not Drupal 6.
     if (DrupalPractice_Project::getCoreVersion($phpcsFile) !== '7.x') {
         return;
     }
     $fileName = substr(basename($phpcsFile->getFilename()), 0, -7);
     $tokens = $phpcsFile->getTokens();
     if ($tokens[$stackPtr]['content'] !== $fileName . '_init' && $tokens[$stackPtr]['content'] !== $fileName . '_page_build') {
         return;
     }
     // Search in the function body for drupal_add_css() calls.
     $string = $phpcsFile->findNext(T_STRING, $tokens[$functionPtr]['scope_opener'], $tokens[$functionPtr]['scope_closer']);
     while ($string !== false) {
         if ($tokens[$string]['content'] === 'drupal_add_css' || $tokens[$string]['content'] === 'drupal_add_js') {
             $opener = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $string + 1, null, true);
             if ($opener !== false && $tokens[$opener]['code'] === T_OPEN_PARENTHESIS) {
                 if ($tokens[$stackPtr]['content'] === $fileName . '_init') {
                     $warning = 'Do not use %s() in hook_init(), move it to your page/form callback or use hook_page_build() instead';
                     $phpcsFile->addWarning($warning, $string, 'AddFunctionFound', array($tokens[$string]['content']));
                 } else {
                     $warning = 'Do not use %s() in hook_page_build(), use #attached on the $page render array instead';
                     $phpcsFile->addWarning($warning, $string, 'AddFunctionFoundPageBuild', array($tokens[$string]['content']));
                 }
             }
         }
         $string = $phpcsFile->findNext(T_STRING, $string + 1, $tokens[$functionPtr]['scope_closer']);
     }
     //end while
 }
Example #26
0
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     // check line endings
     if ($phpcsFile->eolChar !== "\n") {
         $phpcsFile->addError('We expect lines to end with "\\n".', $stackPtr);
     }
     // get the tokens
     $tokens = $phpcsFile->getTokens();
     // check if there is a newline after the opening tag
     if (T_OPEN_TAG === $tokens[$stackPtr]['code']) {
         // check if next line is empty
         if ($tokens[$stackPtr + 1]['content'] != "\n") {
             $phpcsFile->addError('After "<?php" we expect an empty line.', $stackPtr);
         }
     }
     // check if there is a before after the closing tag
     if (T_CLOSE_TAG === $tokens[$stackPtr]['code']) {
         // get all lines
         $lines = file($phpcsFile->getFilename());
         // check if line before tag is empty
         if (isset($lines[$tokens[$stackPtr]['line'] - 2]) && $lines[$tokens[$stackPtr]['line'] - 2] != "\n") {
             $phpcsFile->addError('Before "?>" we expect an empty line.', $stackPtr);
         }
     }
     // cleanup
     unset($tokens);
     unset($lines);
 }
Example #27
0
 /**
  * Generates a text diff of the original file and the new content.
  *
  * @param string $filePath Optional file path to diff the file against.
  *                         If not specified, the original version of the
  *                         file will be used.
  *
  * @return string
  */
 public function generateDiff($filePath = null)
 {
     if ($filePath === null) {
         $filePath = $this->_currentFile->getFilename();
     }
     $cwd = getcwd() . DIRECTORY_SEPARATOR;
     $filename = str_replace($cwd, '', $filePath);
     $contents = $this->getContents();
     if (function_exists('sys_get_temp_dir') === true) {
         // This is needed for HHVM support, but only available from 5.2.1.
         $tempName = tempnam(sys_get_temp_dir(), 'phpcs-fixer');
         $fixedFile = fopen($tempName, 'w');
     } else {
         $fixedFile = tmpfile();
         $data = stream_get_meta_data($fixedFile);
         $tempName = $data['uri'];
     }
     fwrite($fixedFile, $contents);
     // We must use something like shell_exec() because whitespace at the end
     // of lines is critical to diff files.
     $cmd = "diff -u -L\"{$filename}\" -LPHP_CodeSniffer \"{$filename}\" \"{$tempName}\"";
     $diff = shell_exec($cmd);
     fclose($fixedFile);
     if (is_file($tempName) === true) {
         unlink($tempName);
     }
     return $diff;
 }
 /**
  * Processes the tokens that this sniff is interested in.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
  * @param int                  $stackPtr  The position in the stack where
  *                                        the token was found.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $fileName = $phpcsFile->getFilename();
     $csslintPath = PHP_CodeSniffer::getConfigData('csslint_path');
     if ($csslintPath === null) {
         return;
     }
     $cmd = $csslintPath . ' ' . escapeshellarg($fileName);
     exec($cmd, $output, $retval);
     if (is_array($output) === false) {
         return;
     }
     $count = count($output);
     for ($i = 0; $i < $count; $i++) {
         $matches = array();
         $numMatches = preg_match('/(error|warning) at line (\\d+)/', $output[$i], $matches);
         if ($numMatches === 0) {
             continue;
         }
         $line = (int) $matches[2];
         $message = 'csslint says: ' . $output[$i + 1];
         // First line is message with error line and error code.
         // Second is error message.
         // Third is wrong line in file.
         // Fourth is empty line.
         $i += 4;
         $phpcsFile->addWarningOnLine($message, $line, 'ExternalTool');
     }
     //end for
     // Ignore the rest of the file.
     return $phpcsFile->numTokens + 1;
 }
 /**
  * Processes this sniff, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param int                  $stackPtr  The position of the current token in
  *                                        the stack passed in $tokens.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $fileName = $phpcsFile->getFilename();
     $matches = array();
     if (preg_match('|/systems/(.*)/([^/]+)?actions.inc$|i', $fileName, $matches) === 0) {
         // Not an actions file.
         return;
     }
     $ownClass = $matches[2];
     $tokens = $phpcsFile->getTokens();
     $typeName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, $stackPtr + 2, null, false, true);
     $typeName = trim($tokens[$typeName]['content'], " '");
     switch (strtolower($tokens[$stackPtr + 1]['content'])) {
         case 'includesystem':
             $included = strtolower($typeName);
             break;
         case 'includeasset':
             $included = strtolower($typeName) . 'assettype';
             break;
         case 'includewidget':
             $included = strtolower($typeName) . 'widgettype';
             break;
         default:
             return;
     }
     if ($included === strtolower($ownClass)) {
         $error = "You do not need to include \"%s\" from within the system's own actions file";
         $data = array($ownClass);
         $phpcsFile->addError($error, $stackPtr, 'NotRequired', $data);
     }
 }
Example #30
0
 /**
  * Processes this test, when one of its tokens is encountered.
  *
  * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
  * @param int                  $stackPtr  The position of the current token in
  *                                        the stack passed in $tokens.
  *
  * @return void
  */
 public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
 {
     $phpPath = PHP_CodeSniffer::getConfigData('php_path');
     if ($phpPath === null) {
         return;
     }
     $fileName = $phpcsFile->getFilename();
     $cmd = "{$phpPath} -l \"{$fileName}\" 2>&1";
     $output = shell_exec($cmd);
     $matches = array();
     if (preg_match('/^.*error:(.*) in .* on line ([0-9]+)/', $output, $matches)) {
         $error = trim($matches[1]);
         $line = (int) $matches[2];
         $tokens = $phpcsFile->getTokens();
         $numLines = $tokens[$phpcsFile->numTokens - 1]['line'];
         if ($line > $numLines) {
             $line = $numLines;
         }
         foreach ($tokens as $id => $token) {
             if ($token['line'] === $line) {
                 $phpcsFile->addError("PHP syntax error: {$error}", $id, 'PHPSyntax');
                 break;
             }
         }
     }
 }