File: IncludeSystemSniff.php

package info (click to toggle)
php-codesniffer 1.3.4-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 4,092 kB
  • sloc: php: 30,445; xml: 3,768; makefile: 15; pascal: 8; sh: 6
file content (329 lines) | stat: -rw-r--r-- 13,504 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
<?php
/**
 * Ensures that systems, asset types and libs are included before they are used.
 *
 * PHP version 5
 *
 * @category  PHP
 * @package   PHP_CodeSniffer_MySource
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */

if (class_exists('PHP_CodeSniffer_Standards_AbstractScopeSniff', true) === false) {
    $error = 'Class PHP_CodeSniffer_Standards_AbstractScopeSniff not found';
    throw new PHP_CodeSniffer_Exception($error);
}

/**
 * Ensures that systems, asset types and libs are included before they are used.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer_MySource
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @copyright 2006-2011 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @version   Release: 1.3.4
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class MySource_Sniffs_Channels_IncludeSystemSniff extends PHP_CodeSniffer_Standards_AbstractScopeSniff
{

    /**
     * A list of classes that don't need to be included.
     *
     * @var array(string)
     */
    private $_ignore = array(
                        'self',
                        'parent',
                        'channels',
                        'basesystem',
                        'dal',
                        'init',
                        'pdo',
                        'util',
                        'ziparchive',
                        'phpunit_framework_assert',
                        'abstractmysourceunittest',
                        'abstractdatacleanunittest',
                        'exception',
                        'abstractwidgetwidgettype',
                        'domdocument',
                       );


    /**
     * Constructs a Squiz_Sniffs_Scope_MethodScopeSniff.
     */
    public function __construct()
    {
        parent::__construct(array(T_FUNCTION), array(T_DOUBLE_COLON, T_EXTENDS), true);

    }//end __construct()


    /**
     * Processes the function tokens within the class.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The file where this token was found.
     * @param integer              $stackPtr  The position where the token was found.
     * @param integer              $currScope The current scope opener token.
     *
     * @return void
     */
    protected function processTokenWithinScope(
        PHP_CodeSniffer_File $phpcsFile,
        $stackPtr,
        $currScope
    ) {
        $tokens = $phpcsFile->getTokens();

        // Determine the name of the class that the static function
        // is being called on.
        $classNameToken = $phpcsFile->findPrevious(
            T_WHITESPACE,
            ($stackPtr - 1),
            null,
            true
        );

        $className = $tokens[$classNameToken]['content'];
        if (in_array(strtolower($className), $this->_ignore) === true) {
            return;
        }

        $includedClasses = array();

        $fileName = strtolower($phpcsFile->getFilename());
        $matches  = array();
        if (preg_match('|/systems/(.*)/([^/]+)?actions.inc$|', $fileName, $matches) !== 0) {
            // This is an actions file, which means we don't
            // have to include the system in which it exists.
            $includedClasses[] = $matches[2];

            // Or a system it implements.
            $class      = $phpcsFile->getCondition($stackPtr, T_CLASS);
            $implements = $phpcsFile->findNext(T_IMPLEMENTS, $class, ($class + 10));
            if ($implements !== false) {
                $implementsClass     = $phpcsFile->findNext(T_STRING, $implements);
                $implementsClassName = strtolower($tokens[$implementsClass]['content']);
                if (substr($implementsClassName, -7) === 'actions') {
                    $includedClasses[] = substr($implementsClassName, 0, -7);
                }
            }
        }

        // Go searching for includeSystem and includeAsset calls within this
        // function, or the inclusion of .inc files, which
        // would be library files.
        for ($i = ($currScope + 1); $i < $stackPtr; $i++) {
            $name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i);
            if ($name !== false) {
                $includedClasses[] = $name;
                // Special case for Widgets cause they are, well, special.
            } else if (strtolower($tokens[$i]['content']) === 'includewidget') {
                $typeName          = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($i + 1));
                $typeName          = trim($tokens[$typeName]['content'], " '");
                $includedClasses[] = strtolower($typeName).'widgettype';
            }
        }

        // Now go searching for includeSystem, includeAsset or require/include
        // calls outside our scope. If we are in a class, look outside the
        // class. If we are not, look outside the function.
        $condPtr = $currScope;
        if ($phpcsFile->hasCondition($stackPtr, T_CLASS) === true) {
            foreach ($tokens[$stackPtr]['conditions'] as $condPtr => $condType) {
                if ($condType === T_CLASS) {
                    break;
                }
            }
        }

        for ($i = 0; $i < $condPtr; $i++) {
            // Skip other scopes.
            if (isset($tokens[$i]['scope_closer']) === true) {
                $i = $tokens[$i]['scope_closer'];
                continue;
            }

            $name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i);
            if ($name !== false) {
                $includedClasses[] = $name;
            }
        }//end for

        // If we are in a testing class, we might have also included
        // some systems and classes in our setUp() method.
        $setupFunction = null;
        if ($phpcsFile->hasCondition($stackPtr, T_CLASS) === true) {
            foreach ($tokens[$stackPtr]['conditions'] as $condPtr => $condType) {
                if ($condType === T_CLASS) {
                    // Is this is a testing class?
                    $name = $phpcsFile->findNext(T_STRING, $condPtr);
                    $name = $tokens[$name]['content'];
                    if (substr($name, -8) === 'UnitTest') {
                        // Look for a method called setUp().
                        $end      = $tokens[$condPtr]['scope_closer'];
                        $function = $phpcsFile->findNext(T_FUNCTION, ($condPtr + 1), $end);
                        while ($function !== false) {
                            $name = $phpcsFile->findNext(T_STRING, $function);
                            if ($tokens[$name]['content'] === 'setUp') {
                                $setupFunction = $function;
                                break;
                            }

                            $function = $phpcsFile->findNext(T_FUNCTION, ($function + 1), $end);
                        }
                    }
                }
            }//end foreach
        }//end if

        if ($setupFunction !== null) {
            $start = ($tokens[$setupFunction]['scope_opener'] + 1);
            $end   = $tokens[$setupFunction]['scope_closer'];
            for ($i = $start; $i < $end; $i++) {
                $name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i);
                if ($name !== false) {
                    $includedClasses[] = $name;
                }
            }
        }//end if

        if (in_array(strtolower($className), $includedClasses) === false) {
            $error = 'Static method called on non-included class or system "%s"; include system with Channels::includeSystem() or include class with require_once';
            $data  = array($className);
            $phpcsFile->addError($error, $stackPtr, 'NotIncludedCall', $data);
        }

    }//end processTokenWithinScope()


    /**
     * Processes a token within the scope that this test is listening to.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
     * @param int                  $stackPtr  The position in the stack where
     *                                        this token was found.
     *
     * @return void
     */
    protected function processTokenOutsideScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        if ($tokens[$stackPtr]['code'] === T_EXTENDS) {
            // Find the class name.
            $classNameToken = $phpcsFile->findNext(T_STRING, ($stackPtr + 1));
            $className      = $tokens[$classNameToken]['content'];
        } else {
            // Determine the name of the class that the static function
            // is being called on.
            $classNameToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
            $className      = $tokens[$classNameToken]['content'];
        }

        // Some systems are always available.
        if (in_array(strtolower($className), $this->_ignore) === true) {
            return;
        }

        $includedClasses = array();

        $fileName = strtolower($phpcsFile->getFilename());
        $matches  = array();
        if (preg_match('|/systems/([^/]+)/([^/]+)?actions.inc$|', $fileName, $matches) !== 0) {
            // This is an actions file, which means we don't
            // have to include the system in which it exists
            // We know the system from the path.
            $includedClasses[] = $matches[1];
        }

        // Go searching for includeSystem, includeAsset or require/include
        // calls outside our scope.
        for ($i = 0; $i < $stackPtr; $i++) {
            // Skip classes and functions as will we never get
            // into their scopes when including this file, although
            // we have a chance of getting into IF's, WHILE's etc.
            $ignoreTokens = array(
                             T_CLASS,
                             T_INTERFACE,
                             T_FUNCTION,
                            );

            if (in_array($tokens[$i]['code'], $ignoreTokens) === true
                && isset($tokens[$i]['scope_closer']) === true
            ) {
                $i = $tokens[$i]['scope_closer'];
                continue;
            }

            $name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i);
            if ($name !== false) {
                $includedClasses[] = $name;
                // Special case for Widgets cause they are, well, special.
            } else if (strtolower($tokens[$i]['content']) === 'includewidget') {
                $typeName          = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($i + 1));
                $typeName          = trim($tokens[$typeName]['content'], " '");
                $includedClasses[] = strtolower($typeName).'widgettype';
            }
        }//end for

        if (in_array(strtolower($className), $includedClasses) === false) {
            if ($tokens[$stackPtr]['code'] === T_EXTENDS) {
                $error = 'Class extends non-included class or system "%s"; include system with Channels::includeSystem() or include class with require_once';
                $data  = array($className);
                $phpcsFile->addError($error, $stackPtr, 'NotIncludedExtends', $data);
            } else {
                $error = 'Static method called on non-included class or system "%s"; include system with Channels::includeSystem() or include class with require_once';
                $data  = array($className);
                $phpcsFile->addError($error, $stackPtr, 'NotIncludedCall', $data);
            }
        }

    }//end processTokenOutsideScope()


    /**
     * Determines the included class name from given token.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The file where this token was found.
     * @param array                $tokens    The array of file tokens.
     * @param int                  $stackPtr  The position in the tokens array of the
     *                                        potentially included class.
     *
     * @return string
     */
    protected function getIncludedClassFromToken(
        PHP_CodeSniffer_File $phpcsFile,
        array $tokens,
        $stackPtr
    ) {
        if (strtolower($tokens[$stackPtr]['content']) === 'includesystem') {
            $systemName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($stackPtr + 1));
            $systemName = trim($tokens[$systemName]['content'], " '");
            return strtolower($systemName);
        } else if (strtolower($tokens[$stackPtr]['content']) === 'includeasset') {
            $typeName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($stackPtr + 1));
            $typeName = trim($tokens[$typeName]['content'], " '");
            return strtolower($typeName).'assettype';
        } else if (in_array($tokens[$stackPtr]['code'], PHP_CodeSniffer_Tokens::$includeTokens) === true) {
            $filePath = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($stackPtr + 1));
            $filePath = $tokens[$filePath]['content'];
            $filePath = trim($filePath, " '");
            $filePath = basename($filePath, '.inc');
            return strtolower($filePath);
        }

        return false;

    }//end getIncludedClassFromToken()


}//end class

?>