Subversion Repositories Applications.framework

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
5 aurelien 1
<?php
2
/**
3
 * A class to process command line phpcs scripts.
4
 *
5
 * PHP version 5
6
 *
7
 * @category  PHP
8
 * @package   PHP_CodeSniffer
9
 * @author    Greg Sherwood <gsherwood@squiz.net>
10
 * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
11
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
12
 * @version   CVS: $Id: CLI.php,v 1.9 2008/12/21 23:54:14 squiz Exp $
13
 * @link      http://pear.php.net/package/PHP_CodeSniffer
14
 */
15
 
16
if (is_file(dirname(__FILE__).'/../CodeSniffer.php') === true) {
17
    include_once dirname(__FILE__).'/../CodeSniffer.php';
18
} else {
19
    include_once 'PHP/CodeSniffer.php';
20
}
21
 
22
/**
23
 * A class to process command line phpcs scripts.
24
 *
25
 * @category  PHP
26
 * @package   PHP_CodeSniffer
27
 * @author    Greg Sherwood <gsherwood@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 PHP_CodeSniffer_CLI
34
{
35
 
36
 
37
    /**
38
     * Exits if the minimum requirements of PHP_CodSniffer are not met.
39
     *
40
     * @return array
41
     */
42
    public function checkRequirements()
43
    {
44
        // Check the PHP version.
45
        if (version_compare(PHP_VERSION, '5.1.2') === -1) {
46
            echo 'ERROR: PHP_CodeSniffer requires PHP version 5.1.2 or greater.'.PHP_EOL;
47
            exit(2);
48
        }
49
 
50
        if (extension_loaded('tokenizer') === false) {
51
            echo 'ERROR: PHP_CodeSniffer requires the tokenizer extension to be enabled.'.PHP_EOL;
52
            exit(2);
53
        }
54
 
55
    }//end checkRequirements()
56
 
57
 
58
    /**
59
     * Get a list of default values for all possible command line arguments.
60
     *
61
     * @return array
62
     */
63
    public function getDefaults()
64
    {
65
        // The default values for config settings.
66
        $defaults['files']       = array();
67
        $defaults['standard']    = null;
68
        $defaults['verbosity']   = 0;
69
        $defaults['local']       = false;
70
        $defaults['showSources'] = false;
71
        $defaults['extensions']  = array();
72
        $defaults['sniffs']      = array();
73
        $defaults['ignored']     = array();
74
        $defaults['reportFile']  = '';
75
        $defaults['generator']   = '';
76
 
77
        $defaults['report'] = PHP_CodeSniffer::getConfigData('report_format');
78
        if ($defaults['report'] === null) {
79
            $defaults['report'] = 'full';
80
        }
81
 
82
        $showWarnings = PHP_CodeSniffer::getConfigData('show_warnings');
83
        if ($showWarnings === null) {
84
            $defaults['showWarnings'] = true;
85
        } else {
86
            $defaults['showWarnings'] = (bool) $showWarnings;
87
        }
88
 
89
        $tabWidth = PHP_CodeSniffer::getConfigData('tab_width');
90
        if ($tabWidth === null) {
91
            $defaults['tabWidth'] = 0;
92
        } else {
93
            $defaults['tabWidth'] = (int) $tabWidth;
94
        }
95
 
96
        return $defaults;
97
 
98
    }//end getDefaults()
99
 
100
 
101
    /**
102
     * Process the command line arguments and returns the values.
103
     *
104
     * @return array
105
     */
106
    public function getCommandLineValues()
107
    {
108
        $values = $this->getDefaults();
109
 
110
        for ($i = 1; $i < $_SERVER['argc']; $i++) {
111
            $arg = $_SERVER['argv'][$i];
112
            if ($arg{0} === '-') {
113
                if ($arg === '-' || $arg === '--') {
114
                    // Empty argument, ignore it.
115
                    continue;
116
                }
117
 
118
                if ($arg{1} === '-') {
119
                    $values
120
                        = $this->processLongArgument(substr($arg, 2), $i, $values);
121
                } else {
122
                    $switches = str_split($arg);
123
                    foreach ($switches as $switch) {
124
                        if ($switch === '-') {
125
                            continue;
126
                        }
127
 
128
                        $values = $this->processShortArgument($switch, $i, $values);
129
                    }
130
                }
131
            } else {
132
                $values = $this->processUnknownArgument($arg, $i, $values);
133
            }
134
        }//end for
135
 
136
        return $values;
137
 
138
    }//end getCommandLineValues()
139
 
140
 
141
    /**
142
     * Processes a sort (-e) command line argument.
143
     *
144
     * @param string $arg    The command line argument.
145
     * @param int    $pos    The position of the argument on the command line.
146
     * @param array  $values An array of values determined from CLI args.
147
     *
148
     * @return array The updated CLI values.
149
     * @see getCommandLineValues()
150
     */
151
    public function processShortArgument($arg, $pos, $values)
152
    {
153
        switch ($arg) {
154
        case 'h':
155
        case '?':
156
            $this->printUsage();
157
            exit(0);
158
            break;
159
        case 'i' :
160
            $this->printInstalledStandards();
161
            exit(0);
162
            break;
163
        case 'v' :
164
            $values['verbosity']++;
165
            break;
166
        case 'l' :
167
            $values['local'] = true;
168
            break;
169
        case 's' :
170
            $values['showSources'] = true;
171
            break;
172
        case 'n' :
173
            $values['showWarnings'] = false;
174
            break;
175
        case 'w' :
176
            $values['showWarnings'] = true;
177
            break;
178
        default:
179
            $values = $this->processUnknownArgument('-'.$arg, $pos, $values);
180
        }//end switch
181
 
182
        return $values;
183
 
184
    }//end processShortArgument()
185
 
186
 
187
    /**
188
     * Processes a long (--example) command line argument.
189
     *
190
     * @param string $arg    The command line argument.
191
     * @param int    $pos    The position of the argument on the command line.
192
     * @param array  $values An array of values determined from CLI args.
193
     *
194
     * @return array The updated CLI values.
195
     * @see getCommandLineValues()
196
     */
197
    public function processLongArgument($arg, $pos, $values)
198
    {
199
        switch ($arg) {
200
        case 'help':
201
            $this->printUsage();
202
            exit(0);
203
            break;
204
        case 'version':
205
            echo 'PHP_CodeSniffer version 1.2.0RC1 (beta) ';
206
            echo 'by Squiz Pty Ltd. (http://www.squiz.net)'.PHP_EOL;
207
            exit(0);
208
            break;
209
        case 'config-set':
210
            $key   = $_SERVER['argv'][($pos + 1)];
211
            $value = $_SERVER['argv'][($pos + 2)];
212
            PHP_CodeSniffer::setConfigData($key, $value);
213
            exit(0);
214
            break;
215
        case 'config-delete':
216
            $key = $_SERVER['argv'][($pos + 1)];
217
            PHP_CodeSniffer::setConfigData($key, null);
218
            exit(0);
219
            break;
220
        case 'config-show':
221
            $data = PHP_CodeSniffer::getAllConfigData();
222
            print_r($data);
223
            exit(0);
224
            break;
225
        default:
226
            if (substr($arg, 0, 7) === 'sniffs=') {
227
                $values['sniffs'] = array();
228
 
229
                $sniffs = substr($arg, 7);
230
                $sniffs = explode(',', $sniffs);
231
 
232
                // Convert the sniffs to class names.
233
                foreach ($sniffs as $sniff) {
234
                    $parts = explode('.', $sniff);
235
                    $values['sniffs'][] = $parts[0].'_Sniffs_'.$parts[1].'_'.$parts[2].'Sniff';
236
                }
237
            } else if (substr($arg, 0, 7) === 'report=') {
238
                $values['report'] = substr($arg, 7);
239
                $validReports     = array(
240
                                     'full',
241
                                     'xml',
242
                                     'checkstyle',
243
                                     'csv',
244
                                     'emacs',
245
                                     'source',
246
                                     'summary',
247
                                    );
248
 
249
                if (in_array($values['report'], $validReports) === false) {
250
                    echo 'ERROR: Report type "'.$values['report'].'" not known.'.PHP_EOL;
251
                    exit(2);
252
                }
253
            } else if (substr($arg, 0, 12) === 'report-file=') {
254
                $values['reportFile'] = realpath(substr($arg, 12));
255
 
256
                // It may not exist and return false instead.
257
                if ($values['reportFile'] === false) {
258
                    $values['reportFile'] = substr($arg, 12);
259
                }
260
 
261
                if (is_dir($values['reportFile']) === true) {
262
                    echo 'ERROR: The specified report file path "'.$values['reportFile'].'" is a directory.'.PHP_EOL.PHP_EOL;
263
                    $this->printUsage();
264
                    exit(2);
265
                }
266
 
267
                $dir = dirname($values['reportFile']);
268
                if (is_dir($dir) === false) {
269
                    echo 'ERROR: The specified report file path "'.$values['reportFile'].'" points to a non-existent directory.'.PHP_EOL.PHP_EOL;
270
                    $this->printUsage();
271
                    exit(2);
272
                }
273
            } else if (substr($arg, 0, 9) === 'standard=') {
274
                $values['standard'] = substr($arg, 9);
275
            } else if (substr($arg, 0, 11) === 'extensions=') {
276
                $values['extensions'] = explode(',', substr($arg, 11));
277
            } else if (substr($arg, 0, 7) === 'ignore=') {
278
                // Split the ignore string on commas, unless the comma is escaped
279
                // using 1 or 3 slashes (\, or \\\,).
280
                $values['ignored']= preg_split('/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/', substr($arg, 7));
281
            } else if (substr($arg, 0, 10) === 'generator=') {
282
                $values['generator'] = substr($arg, 10);
283
            } else if (substr($arg, 0, 10) === 'tab-width=') {
284
                $values['tabWidth'] = (int) substr($arg, 10);
285
            } else {
286
                $values = $this->processUnknownArgument('--'.$arg, $pos, $values);
287
            }//end if
288
 
289
            break;
290
        }//end switch
291
 
292
        return $values;
293
 
294
    }//end processLongArgument()
295
 
296
 
297
    /**
298
     * Processes an unknown command line argument.
299
     *
300
     * Assumes all unknown arguments are files and folders to check.
301
     *
302
     * @param string $arg    The command line argument.
303
     * @param int    $pos    The position of the argument on the command line.
304
     * @param array  $values An array of values determined from CLI args.
305
     *
306
     * @return array The updated CLI values.
307
     * @see getCommandLineValues()
308
     */
309
    public function processUnknownArgument($arg, $pos, $values)
310
    {
311
        // We don't know about any additional switches; just files.
312
        if ($arg{0} === '-') {
313
            echo 'ERROR: option "'.$arg.'" not known.'.PHP_EOL.PHP_EOL;
314
            $this->printUsage();
315
            exit(2);
316
        }
317
 
318
        $file = realpath($arg);
319
        if (file_exists($file) === false) {
320
            echo 'ERROR: The file "'.$arg.'" does not exist.'.PHP_EOL.PHP_EOL;
321
            $this->printUsage();
322
            exit(2);
323
        } else {
324
            $values['files'][] = $file;
325
        }
326
 
327
        return $values;
328
 
329
    }//end processUnknownArgument()
330
 
331
 
332
    /**
333
     * Runs PHP_CodeSniffer over files are directories.
334
     *
335
     * @param array $values An array of values determined from CLI args.
336
     *
337
     * @return int The number of error and warning messages shown.
338
     * @see getCommandLineValues()
339
     */
340
    public function process($values=array())
341
    {
342
        if (empty($values) === true) {
343
            $values = $this->getCommandLineValues();
344
        }
345
 
346
        if ($values['generator'] !== '') {
347
            $phpcs = new PHP_CodeSniffer($values['verbosity']);
348
            $phpcs->generateDocs(
349
                $values['standard'],
350
                $values['files'],
351
                $values['generator']
352
            );
353
            exit(0);
354
        }
355
 
356
        if (empty($values['files']) === true) {
357
            echo 'ERROR: You must supply at least one file or directory to process.'.PHP_EOL.PHP_EOL;
358
            $this->printUsage();
359
            exit(2);
360
        }
361
 
362
        $values['standard'] = $this->validateStandard($values['standard']);
363
        if (PHP_CodeSniffer::isInstalledStandard($values['standard']) === false) {
364
            // They didn't select a valid coding standard, so help them
365
            // out by letting them know which standards are installed.
366
            echo 'ERROR: the "'.$values['standard'].'" coding standard is not installed. ';
367
            $this->printInstalledStandards();
368
            exit(2);
369
        }
370
 
371
        $phpcs = new PHP_CodeSniffer($values['verbosity'], $values['tabWidth']);
372
 
373
        // Set file extensions if they were specified. Otherwise,
374
        // let PHP_CodeSniffer decide on the defaults.
375
        if (empty($values['extensions']) === false) {
376
            $phpcs->setAllowedFileExtensions($values['extensions']);
377
        }
378
 
379
        // Set ignore patterns if they were specified.
380
        if (empty($values['ignored']) === false) {
381
            $phpcs->setIgnorePatterns($values['ignored']);
382
        }
383
 
384
        $phpcs->process(
385
            $values['files'],
386
            $values['standard'],
387
            $values['sniffs'],
388
            $values['local']
389
        );
390
 
391
        return $this->printErrorReport(
392
            $phpcs,
393
            $values['report'],
394
            $values['showWarnings'],
395
            $values['showSources'],
396
            $values['reportFile']
397
        );
398
 
399
    }//end process()
400
 
401
 
402
    /**
403
     * Prints the error report.
404
     *
405
     * @param PHP_CodeSniffer $phpcs        The PHP_CodeSniffer object containing
406
     *                                      the errors.
407
     * @param string          $report       The type of report to print.
408
     * @param bool            $showWarnings TRUE if warnings should also be printed.
409
     * @param bool            $showSources  TRUE if the report should show error sources
410
     *                                      (not used by all reports).
411
     * @param string          $reportFile   A file to log the report out to.
412
     *
413
     * @return int The number of error and warning messages shown.
414
     */
415
    public function printErrorReport($phpcs, $report, $showWarnings, $showSources, $reportFile='')
416
    {
417
        if ($reportFile !== '') {
418
            ob_start();
419
        }
420
 
421
        switch ($report) {
422
        case 'xml':
423
            $numErrors = $phpcs->printXMLErrorReport($showWarnings);
424
            break;
425
        case 'checkstyle':
426
            $numErrors = $phpcs->printCheckstyleErrorReport($showWarnings);
427
            break;
428
        case 'csv':
429
            $numErrors = $phpcs->printCSVErrorReport($showWarnings);
430
            break;
431
        case 'emacs':
432
            $numErrors = $phpcs->printEmacsErrorReport($showWarnings);
433
            break;
434
        case 'summary':
435
            $numErrors = $phpcs->printErrorReportSummary($showWarnings, $showSources);
436
            break;
437
        case 'source':
438
            $numErrors = $phpcs->printSourceReport($showWarnings, $showSources);
439
            break;
440
        default:
441
            $numErrors = $phpcs->printErrorReport($showWarnings, $showSources);
442
            break;
443
        }
444
 
445
        if ($reportFile !== '') {
446
            $report = ob_get_contents();
447
            ob_end_flush();
448
 
449
            $report = trim($report);
450
            file_put_contents($reportFile, "$report\n");
451
        }
452
 
453
        return $numErrors;
454
 
455
    }//end printErrorReport()
456
 
457
 
458
    /**
459
     * Convert the passed standard into a valid standard.
460
     *
461
     * Checks things like default values and case.
462
     *
463
     * @param string $standard The standard to validate.
464
     *
465
     * @return string
466
     */
467
    public function validateStandard($standard)
468
    {
469
        if ($standard === null) {
470
            // They did not supply a standard to use.
471
            // Try to get the default from the config system.
472
            $standard = PHP_CodeSniffer::getConfigData('default_standard');
473
            if ($standard === null) {
474
                $standard = 'PEAR';
475
            }
476
        }
477
 
478
        // Check if the standard name is valid. If not, check that the case
479
        // was not entered incorrectly.
480
        if (PHP_CodeSniffer::isInstalledStandard($standard) === false) {
481
            $installedStandards = PHP_CodeSniffer::getInstalledStandards();
482
            foreach ($installedStandards as $validStandard) {
483
                if (strtolower($standard) === strtolower($validStandard)) {
484
                    $standard = $validStandard;
485
                    break;
486
                }
487
            }
488
        }
489
 
490
        return $standard;
491
 
492
    }//end validateStandard()
493
 
494
 
495
    /**
496
     * Prints out the usage information for this script.
497
     *
498
     * @return void
499
     */
500
    public function printUsage()
501
    {
502
        echo 'Usage: phpcs [-nwlsvi] [--report=<report>] [--report-file=<reportfile>]'.PHP_EOL;
503
        echo '    [--config-set key value] [--config-delete key] [--config-show]'.PHP_EOL;
504
        echo '    [--standard=<standard>] [--sniffs=<sniffs>]'.PHP_EOL;
505
        echo '    [--extensions=<extensions>] [--ignore=<patterns>]'.PHP_EOL;
506
        echo '    [--generator=<generator>] [--tab-width=<width>] <file> ...'.PHP_EOL;
507
        echo '        -n           Do not print warnings'.PHP_EOL;
508
        echo '        -w           Print both warnings and errors (on by default)'.PHP_EOL;
509
        echo '        -l           Local directory only, no recursion'.PHP_EOL;
510
        echo '        -s           Show sniff codes in all reports'.PHP_EOL;
511
        echo '        -v[v][v]     Print verbose output'.PHP_EOL;
512
        echo '        -i           Show a list of installed coding standards'.PHP_EOL;
513
        echo '        --help       Print this help message'.PHP_EOL;
514
        echo '        --version    Print version information'.PHP_EOL;
515
        echo '        <file>       One or more files and/or directories to check'.PHP_EOL;
516
        echo '        <extensions> A comma separated list of file extensions to check'.PHP_EOL;
517
        echo '                     (only valid if checking a directory)'.PHP_EOL;
518
        echo '        <patterns>   A comma separated list of patterns that are used'.PHP_EOL;
519
        echo '                     to ignore directories and files'.PHP_EOL;
520
        echo '        <sniffs>     A comma separated list of sniff codes to limit the check to'.PHP_EOL;
521
        echo '                     (all sniffs must be part of the specified standard)'.PHP_EOL;
522
        echo '        <standard>   The name of the coding standard to use'.PHP_EOL;
523
        echo '        <width>      The number of spaces each tab represents'.PHP_EOL;
524
        echo '        <generator>  The name of a doc generator to use'.PHP_EOL;
525
        echo '                     (forces doc generation instead of checking)'.PHP_EOL;
526
        echo '        <report>     Print either the "full", "xml", "checkstyle",'.PHP_EOL;
527
        echo '                     "csv", "emacs", "source" or "summary" report'.PHP_EOL;
528
        echo '                     (the "full" report is printed by default)'.PHP_EOL;
529
        echo '        <reportfile> Write the report to the specified file path'.PHP_EOL;
530
        echo '                     (report is also written to screen)'.PHP_EOL;
531
 
532
    }//end printUsage()
533
 
534
 
535
    /**
536
     * Prints out a list of installed coding standards.
537
     *
538
     * @return void
539
     */
540
    public function printInstalledStandards()
541
    {
542
        $installedStandards = PHP_CodeSniffer::getInstalledStandards();
543
        $numStandards       = count($installedStandards);
544
 
545
        if ($numStandards === 0) {
546
            echo 'No coding standards are installed.'.PHP_EOL;
547
        } else {
548
            $lastStandard = array_pop($installedStandards);
549
            if ($numStandards === 1) {
550
                echo 'The only coding standard installed is $lastStandard'.PHP_EOL;
551
            } else {
552
                $standardList  = implode(', ', $installedStandards);
553
                $standardList .= ' and '.$lastStandard;
554
                echo 'The installed coding standards are '.$standardList.PHP_EOL;
555
            }
556
        }
557
 
558
    }//end printInstalledStandards()
559
 
560
 
561
}//end class
562
 
563
?>