ClosingLocationCommentSniff::process()   C
last analyzed

Complexity

Conditions 11
Paths 23

Size

Total Lines 50
Code Lines 31

Duplication

Lines 24
Ratio 48 %

Importance

Changes 0
Metric Value
cc 11
eloc 31
nc 23
nop 2
dl 24
loc 50
rs 5.4893
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * CodeIgniter_Sniffs_Files_ClosingLocationCommentSniff.
4
 *
5
 * PHP version 5
6
 *
7
 * @category  PHP
8
 * @package   PHP_CodeSniffer
9
 * @author    Thomas Ernest <[email protected]>
10
 * @copyright 2006 Thomas Ernest
11
 * @license   http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
12
 * @link      http://pear.php.net/package/PHP_CodeSniffer
13
 */
14
15
/**
16
 * CodeIgniter_Sniffs_Files_ClosingLocationCommentSniff.
17
 *
18
 * Ensures that a comment containing the file location exists at the end of file.
19
 * Only other comments and whitespaces are allowed between this comment and
20
 * the end of file.
21
 *
22
 * It may be all kind of comment like multi-line and inline C-style comments as
23
 * well as PERL-style comments. Any number of white may separate comment delimiters
24
 * from comment content. However, content has to be equal to template
25
 * "Location: <file_path_relative_to_application_root>".
26
 * Comparison between content and template is case-sensitive.
27
 *
28
 * There are several ways to configure the application root. In order of priority :
29
 *   - Configuration variable ci_application_root.
30
 *   - Rule property applicationRoot.
31
 *   - Default value '/application/'
32
 *
33
 * @category  PHP
34
 * @package   PHP_CodeSniffer
35
 * @author    Thomas Ernest <[email protected]>
36
 * @copyright 2006 Thomas Ernest
37
 * @license   http://thomas.ernest.fr/developement/php_cs/licence GNU General Public License
38
 * @link      http://pear.php.net/package/PHP_CodeSniffer
39
 */
40
41
namespace CodeIgniter\Sniffs\Files;
42
43
use PHP_CodeSniffer\Files\File;
44
use PHP_CodeSniffer\Util\Common;
45
46
class ClosingLocationCommentSniff extends AbstractClosingCommentSniff
47
{
48
    public $applicationRoot = '/application/';
49
50
    /**
51
     * Returns an array of tokens this test wants to listen for.
52
     *
53
     * @return array
54
     */
55
    public function register()
56
    {
57
        return array(
58
            T_OPEN_TAG
59
        );
60
61
    }//end register()
62
63
64
    /**
65
     * Processes this test, when one of its tokens is encountered.
66
     *
67
     * @param File $phpcsFile The current file being scanned.
68
     * @param int                  $stackPtr  The position of the current token
69
     *                                        in the stack passed in $tokens.
70
     *
71
     * @return void
72
     */
73
    public function process(File $phpcsFile, $stackPtr)
74
    {
75
        // We are only interested if this is the first open tag.
76 View Code Duplication
        if ($stackPtr !== 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
77
            if ($phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)) !== false) {
78
                return;
79
            }
80
        }
81
82
        $filePath = $phpcsFile->getFilename();
83
        $tokens = $phpcsFile->getTokens();
84
        // removes the application root from the beginning of the file path
85
        $locationPath = self::_getLocationPath($filePath, $this->_getAppRoot());
86
        // add an error, if application root doesn't exist in current file path
87
        if (false === $locationPath) {
88
            $error = 'Unable to find "' . $this->_getAppRoot() . '" in file path "' . $filePath . '". Please set your project\'s application root.';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 148 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
89
            $phpcsFile->addError($error, count($tokens) - 1);
0 ignored issues
show
Bug introduced by
The call to addError() misses a required argument $code.

This check looks for function calls that miss required arguments.

Loading history...
90
            return;
91
        }
92
        // generates the expected comment
93
        $commentTemplate = "Location: $locationPath";
94
95
        $currentToken = count($tokens) - 1;
96
        $hasClosingLocationComment = false;
97
        $isNotAWhitespaceOrAComment = false;
98 View Code Duplication
        while ($currentToken >= 0
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
99
            && ! $isNotAWhitespaceOrAComment
100
            && ! $hasClosingLocationComment
101
        ) {
102
            $token = $tokens[$currentToken];
103
            $tokenCode = $token['code'];
104
            if (T_COMMENT === $tokenCode) {
105
                $commentString = self::_getCommentContent($token['content']);
106
                if (0 === strcmp($commentString, $commentTemplate)) {
107
                    $hasClosingLocationComment = true;
108
                }
109
            } else if (T_WHITESPACE === $tokenCode) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
110
                // Whitespaces are allowed between the closing file comment,
111
                //other comments and end of file
112
            } else {
113
                $isNotAWhitespaceOrAComment = true;
114
            }
115
            $currentToken--;
116
        }
117
118
        if ( ! $hasClosingLocationComment) {
119
            $error = 'No comment block marks the end of file instead of the closing PHP tag. Please add a comment block containing only "' . $commentTemplate . '".';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 165 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
120
            $phpcsFile->addError($error, $currentToken);
0 ignored issues
show
Bug introduced by
The call to addError() misses a required argument $code.

This check looks for function calls that miss required arguments.

Loading history...
121
        }
122
    }//end process()
123
124
125
    /**
126
     * Returns the relative path from $appRoot to $filePath, or false if
127
     * $appRoot cannot be found in $filePath, because $appRoot is not a parent
128
     * of $filePath.
129
     *
130
     * @param string $filePath Full path to the file being proceed.
131
     * @param string $appRoot  Partial or full path to the CodeIgniter
132
     * application root of the file being proceed. It must not contain the
133
     * full path to the application root, but at least the name of the
134
     * application root. Parent directory of the application root are allowed
135
     * but not mandatory.
136
     *
137
     * @return string|bool The relative path from $appRoot to $filePath, or
138
     * false if $appRoot cannot be found in $filePath.
139
     */
140
    private static function _getLocationPath ($filePath, $appRoot)
141
    {
142
        // removes the path to application root
143
        // from the beginning of the file path
144
        $appRootAt = strpos($filePath, $appRoot);
145
        if (false === $appRootAt) {
146
            return false;
147
        }
148
        $localPath = substr($filePath, $appRootAt + strlen($appRoot));
149
        // ensures the location path to be a relative path starting with "./".
150
        if ( ! self::_stringStartsWith($localPath, './')) {
151
            $localPath = './' . $localPath;
152
        } else if ( ! self::_stringStartsWith($localPath, '.')
153
            && self::_stringStartsWith($localPath, '/')
154
        ) {
155
            $localPath = '.' . $localPath;
156
        }
157
        return $localPath;
158
    }//end _getLocationPath()
159
160
161
    /**
162
     * Returns the application root that should be used first.
163
     *
164
     * There are several ways to configure the application root.
165
     * In order of priority :
166
     *   - Configuration variable ci_application_root.
167
     *   - Rule property applicationRoot.
168
     *   - Default value '/application/'
169
     *
170
     * @return string Path to your project application root.
171
     */
172
    private function _getAppRoot()
173
    {
174
        $appRoot = Common::getConfigData('ci_application_root');
0 ignored issues
show
Bug introduced by
The method getConfigData() does not seem to exist on object<PHP_CodeSniffer\Util\Common>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
175
        if (null === $appRoot) {
176
            $appRoot = $this->applicationRoot;
177
        }
178
        return $appRoot;
179
    }//end _getAppRoot()
180
}//end class
181
182
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
183