Subversion Repositories Applications.framework

Rev

Rev 5 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
5 aurelien 1
<?php
2
/**
3
 * Generic_Sniffs_Whitespace_ScopeIndentSniff.
4
 *
5
 * PHP version 5
6
 *
7
 * @category  PHP
8
 * @package   PHP_CodeSniffer
9
 * @author    Greg Sherwood <gsherwood@squiz.net>
10
 * @author    Marc McIntyre <mmcintyre@squiz.net>
11
 * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
12
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
34 aurelien 13
 * @version   CVS: $Id: ScopeIndentSniff.php 34 2009-04-09 07:34:39Z aurelien $
5 aurelien 14
 * @link      http://pear.php.net/package/PHP_CodeSniffer
15
 */
16
 
17
/**
18
 * Generic_Sniffs_Whitespace_ScopeIndentSniff.
19
 *
20
 * Checks that control structures are structured correctly, and their content
21
 * is indented correctly. This sniff will throw errors if tabs are used
22
 * for indentation rather than spaces.
23
 *
24
 * @category  PHP
25
 * @package   PHP_CodeSniffer
26
 * @author    Greg Sherwood <gsherwood@squiz.net>
27
 * @author    Marc McIntyre <mmcintyre@squiz.net>
28
 * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
29
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
30
 * @version   Release: 1.2.0RC1
31
 * @link      http://pear.php.net/package/PHP_CodeSniffer
32
 */
33
class Generic_Sniffs_WhiteSpace_ScopeIndentSniff implements PHP_CodeSniffer_Sniff
34
{
35
 
36
    /**
37
     * The number of spaces code should be indented.
38
     *
39
     * @var int
40
     */
41
    protected $indent = 4;
42
 
43
    /**
44
     * Does the indent need to be exactly right.
45
     *
46
     * If TRUE, indent needs to be exactly $ident spaces. If FALSE,
47
     * indent needs to be at least $ident spaces (but can be more).
48
     *
49
     * @var bool
50
     */
51
    protected $exact = false;
52
 
53
    /**
54
     * Any scope openers that should not cause an indent.
55
     *
56
     * @var array(int)
57
     */
58
    protected $nonIndentingScopes = array();
59
 
60
 
61
    /**
62
     * Returns an array of tokens this test wants to listen for.
63
     *
64
     * @return array
65
     */
66
    public function register()
67
    {
68
        return PHP_CodeSniffer_Tokens::$scopeOpeners;
69
 
70
    }//end register()
71
 
72
 
73
    /**
74
     * Processes this test, when one of its tokens is encountered.
75
     *
76
     * @param PHP_CodeSniffer_File $phpcsFile All the tokens found in the document.
77
     * @param int                  $stackPtr  The position of the current token
78
     *                                        in the stack passed in $tokens.
79
     *
80
     * @return void
81
     */
82
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
83
    {
84
        $tokens = $phpcsFile->getTokens();
85
 
86
        // If this is an inline condition (ie. there is no scope opener), then
87
        // return, as this is not a new scope.
88
        if (isset($tokens[$stackPtr]['scope_opener']) === false) {
89
            return;
90
        }
91
 
92
        if ($tokens[$stackPtr]['code'] === T_ELSE) {
93
            $next = $phpcsFile->findNext(
94
                PHP_CodeSniffer_Tokens::$emptyTokens,
95
                ($stackPtr + 1),
96
                null,
97
                true
98
            );
99
 
100
            // We will handle the T_IF token in another call to process.
101
            if ($tokens[$next]['code'] === T_IF) {
102
                return;
103
            }
104
        }
105
 
106
        // Find the first token on this line.
107
        $firstToken = $stackPtr;
108
        for ($i = $stackPtr; $i >= 0; $i--) {
109
            // Record the first code token on the line.
110
            if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$emptyTokens) === false) {
111
                $firstToken = $i;
112
            }
113
 
114
            // It's the start of the line, so we've found our first php token.
115
            if ($tokens[$i]['column'] === 1) {
116
                break;
117
            }
118
        }
119
 
120
        // Based on the conditions that surround this token, determine the
121
        // indent that we expect this current content to be.
122
        $expectedIndent = $this->calculateExpectedIndent($tokens, $firstToken);
123
 
124
        if ($tokens[$firstToken]['column'] !== $expectedIndent) {
125
            $error  = 'Line indented incorrectly; expected ';
126
            $error .= ($expectedIndent - 1).' spaces, found ';
127
            $error .= ($tokens[$firstToken]['column'] - 1);
128
            $phpcsFile->addError($error, $stackPtr);
129
        }
130
 
131
        $scopeOpener = $tokens[$stackPtr]['scope_opener'];
132
        $scopeCloser = $tokens[$stackPtr]['scope_closer'];
133
 
134
        // Some scopes are expected not to have indents.
135
        if (in_array($tokens[$firstToken]['code'], $this->nonIndentingScopes) === false) {
136
            $indent = ($expectedIndent + $this->indent);
137
        } else {
138
            $indent = $expectedIndent;
139
        }
140
 
141
        $newline     = false;
142
        $commentOpen = false;
143
        $inHereDoc   = false;
144
 
145
        // Only loop over the content beween the opening and closing brace, not
146
        // the braces themselves.
147
        for ($i = ($scopeOpener + 1); $i < $scopeCloser; $i++) {
148
 
149
            // If this token is another scope, skip it as it will be handled by
150
            // another call to this sniff.
151
            if (in_array($tokens[$i]['code'], PHP_CodeSniffer_Tokens::$scopeOpeners) === true) {
152
                if (isset($tokens[$i]['scope_opener']) === true) {
153
                    $i = $tokens[$i]['scope_closer'];
154
                } else {
155
                    // If this token does not have a scope_opener indice, then
156
                    // it's probably an inline scope, so let's skip to the next
157
                    // semicolon. Inline scopes include inline if's, abstract
158
                    // methods etc.
159
                    $nextToken = $phpcsFile->findNext(T_SEMICOLON, $i, $scopeCloser);
160
                    if ($nextToken !== false) {
161
                        $i = $nextToken;
162
                    }
163
                }
164
 
165
                continue;
166
            }
167
 
168
            // If this is a HEREDOC then we need to ignore it as the
169
            // whitespace before the contents within the HEREDOC are
170
            // considered part of the content.
171
            if ($tokens[$i]['code'] === T_START_HEREDOC) {
172
                $inHereDoc = true;
173
                continue;
174
            } else if ($inHereDoc === true) {
175
                if ($tokens[$i]['code'] === T_END_HEREDOC) {
176
                    $inHereDoc = false;
177
                }
178
 
179
                continue;
180
            }
181
 
182
            if ($tokens[$i]['column'] === 1) {
183
                // We started a newline.
184
                $newline = true;
185
            }
186
 
187
            if ($newline === true && $tokens[$i]['code'] !== T_WHITESPACE) {
188
                // If we started a newline and we find a token that is not
189
                // whitespace, then this must be the first token on the line that
190
                // must be indented.
191
                $newline    = false;
192
                $firstToken = $i;
193
 
194
                $column = $tokens[$firstToken]['column'];
195
 
196
                // Special case for non-PHP code.
197
                if ($tokens[$firstToken]['code'] === T_INLINE_HTML) {
198
                    $trimmedContentLength
199
                        = strlen(ltrim($tokens[$firstToken]['content']));
200
                    if ($trimmedContentLength === 0) {
201
                        continue;
202
                    }
203
 
204
                    $contentLength = strlen($tokens[$firstToken]['content']);
205
                    $column        = ($contentLength - $trimmedContentLength + 1);
206
                }
207
 
208
                // Check to see if this constant string spans multiple lines.
209
                // If so, then make sure that the strings on lines other than the
210
                // first line are indented appropriately, based on their whitespace.
211
                if (in_array($tokens[$firstToken]['code'], PHP_CodeSniffer_Tokens::$stringTokens) === true) {
212
                    if (in_array($tokens[($firstToken - 1)]['code'], PHP_CodeSniffer_Tokens::$stringTokens) === true) {
213
                        // If we find a string that directly follows another string
214
                        // then its just a string that spans multiple lines, so we
215
                        // don't need to check for indenting.
216
                        continue;
217
                    }
218
                }
219
 
220
                // This is a special condition for T_DOC_COMMENT and C-style
221
                // comments, which contain whitespace between each line.
222
                $comments = array(
223
                             T_COMMENT,
224
                             T_DOC_COMMENT
225
                            );
226
 
227
                if (in_array($tokens[$firstToken]['code'], $comments) === true) {
228
                    $content = trim($tokens[$firstToken]['content']);
229
                    if (preg_match('|^/\*|', $content) !== 0) {
230
                        // Check to see if the end of the comment is on the same line
231
                        // as the start of the comment. If it is, then we don't
232
                        // have to worry about opening a comment.
233
                        if (preg_match('|\*/$|', $content) === 0) {
234
                            // We don't have to calculate the column for the
235
                            // start of the comment as there is a whitespace
236
                            // token before it.
237
                            $commentOpen = true;
238
                        }
239
                    } else if ($commentOpen === true) {
240
                        if ($content === '') {
241
                            // We are in a comment, but this line has nothing on it
242
                            // so let's skip it.
243
                            continue;
244
                        }
245
 
246
                        $contentLength = strlen($tokens[$firstToken]['content']);
247
                        $trimmedContentLength
248
                            = strlen(ltrim($tokens[$firstToken]['content']));
249
 
250
                        $column = ($contentLength - $trimmedContentLength + 1);
251
                        if (preg_match('|\*/$|', $content) !== 0) {
252
                            $commentOpen = false;
253
                        }
254
                    }//end if
255
                }//end if
256
 
257
                // The token at the start of the line, needs to have its' column
258
                // greater than the relative indent we set above. If it is less,
259
                // an error should be shown.
260
                if ($column !== $indent) {
261
                    if ($this->exact === true || $column < $indent) {
262
                        $error  = 'Line indented incorrectly; expected ';
263
                        if ($this->exact === false) {
264
                            $error .= 'at least ';
265
                        }
266
 
267
                        $error .= ($indent - 1).' spaces, found ';
268
                        $error .= ($column - 1);
269
                        $phpcsFile->addError($error, $firstToken);
270
                    }
271
                }
272
            }//end if
273
        }//end for
274
 
275
    }//end process()
276
 
277
 
278
    /**
279
     * Calculates the expected indent of a token.
280
     *
281
     * @param array $tokens   The stack of tokens for this file.
282
     * @param int   $stackPtr The position of the token to get indent for.
283
     *
284
     * @return int
285
     */
286
    protected function calculateExpectedIndent(array $tokens, $stackPtr)
287
    {
288
        $conditionStack = array();
289
 
290
        // Empty conditions array (top level structure).
291
        if (empty($tokens[$stackPtr]['conditions']) === true) {
292
            return 1;
293
        }
294
 
295
        $tokenConditions = $tokens[$stackPtr]['conditions'];
296
        foreach ($tokenConditions as $id => $condition) {
297
            // If it's an indenting scope ie. it's not in our array of
298
            // scopes that don't indent, add it to our condition stack.
299
            if (in_array($condition, $this->nonIndentingScopes) === false) {
300
                $conditionStack[$id] = $condition;
301
            }
302
        }
303
 
304
        return ((count($conditionStack) * $this->indent) + 1);
305
 
306
    }//end calculateExpectedIndent()
307
 
308
 
309
}//end class
310
 
311
?>