/usr/share/php/PHP/CodeSniffer.php is in php-codesniffer 1.5.0~rc2-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 | <?php
/**
* PHP_CodeSniffer tokenises PHP code and detects violations of a
* defined set of coding standards.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
spl_autoload_register(array('PHP_CodeSniffer', 'autoload'));
if (class_exists('PHP_CodeSniffer_Exception', true) === false) {
throw new Exception('Class PHP_CodeSniffer_Exception not found');
}
if (class_exists('PHP_CodeSniffer_File', true) === false) {
throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_File not found');
}
if (class_exists('PHP_CodeSniffer_Tokens', true) === false) {
throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_Tokens not found');
}
if (class_exists('PHP_CodeSniffer_CLI', true) === false) {
throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_CLI not found');
}
if (interface_exists('PHP_CodeSniffer_Sniff', true) === false) {
throw new PHP_CodeSniffer_Exception('Interface PHP_CodeSniffer_Sniff not found');
}
if (interface_exists('PHP_CodeSniffer_MultiFileSniff', true) === false) {
throw new PHP_CodeSniffer_Exception('Interface PHP_CodeSniffer_MultiFileSniff not found');
}
/**
* PHP_CodeSniffer tokenises PHP code and detects violations of a
* defined set of coding standards.
*
* Standards are specified by classes that implement the PHP_CodeSniffer_Sniff
* interface. A sniff registers what token types it wishes to listen for, then
* PHP_CodeSniffer encounters that token, the sniff is invoked and passed
* information about where the token was found in the stack, and the token stack
* itself.
*
* Sniff files and their containing class must be prefixed with Sniff, and
* have an extension of .php.
*
* Multiple PHP_CodeSniffer operations can be performed by re-calling the
* process function with different parameters.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
* @version Release: 1.5.0RC2
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer
{
/**
* The file or directory that is currently being processed.
*
* @var string
*/
protected $file = '';
/**
* A cache of different token types, resolved into arrays.
*
* @var array()
* @see standardiseToken()
*/
private static $_resolveTokenCache = array();
/**
* The directories that the processed rulesets are in.
*
* This is declared static because it is also used in the
* autoloader to look for sniffs outside the PHPCS install.
* This way, standards designed to be installed inside PHPCS can
* also be used from outside the PHPCS Standards directory.
*
* @var string
*/
protected static $rulesetDirs = array();
/**
* The CLI object controlling the run.
*
* @var PHP_CodeSniffer_CLI
*/
public $cli = null;
/**
* The Reporting object controlling report generation.
*
* @var PHP_CodeSniffer_Reporting
*/
public $reporting = null;
/**
* An array of sniff objects that are being used to check files.
*
* @var array(PHP_CodeSniffer_Sniff)
*/
protected $listeners = array();
/**
* An array of sniffs that are being used to check files.
*
* @var array(string)
*/
protected $sniffs = array();
/**
* The listeners array, indexed by token type.
*
* @var array
*/
private $_tokenListeners = array();
/**
* An array of rules from the ruleset.xml file.
*
* It may be empty, indicating that the ruleset does not override
* any of the default sniff settings.
*
* @var array
*/
protected $ruleset = array();
/**
* An array of patterns to use for skipping files.
*
* @var array
*/
protected $ignorePatterns = array();
/**
* An array of extensions for files we will check.
*
* @var array
*/
public $allowedFileExtensions = array(
'php' => 'PHP',
'inc' => 'PHP',
'js' => 'JS',
'css' => 'CSS',
);
/**
* An array of variable types for param/var we will check.
*
* @var array(string)
*/
public static $allowedTypes = array(
'array',
'boolean',
'float',
'integer',
'mixed',
'object',
'string',
);
/**
* Constructs a PHP_CodeSniffer object.
*
* @param int $verbosity The verbosity level.
* 1: Print progress information.
* 2: Print tokenizer debug information.
* 3: Print sniff debug information.
* @param int $tabWidth The number of spaces each tab represents.
* If greater than zero, tabs will be replaced
* by spaces before testing each file.
* @param string $encoding The charset of the sniffed files.
* This is important for some reports that output
* with utf-8 encoding as you don't want it double
* encoding messages.
* @param bool $interactive If TRUE, will stop after each file with errors
* and wait for user input.
*
* @see process()
*/
public function __construct(
$verbosity=0,
$tabWidth=0,
$encoding='iso-8859-1',
$interactive=false
) {
if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
define('PHP_CODESNIFFER_VERBOSITY', $verbosity);
}
if (defined('PHP_CODESNIFFER_TAB_WIDTH') === false) {
define('PHP_CODESNIFFER_TAB_WIDTH', $tabWidth);
}
if (defined('PHP_CODESNIFFER_ENCODING') === false) {
define('PHP_CODESNIFFER_ENCODING', $encoding);
}
if (defined('PHP_CODESNIFFER_INTERACTIVE') === false) {
define('PHP_CODESNIFFER_INTERACTIVE', $interactive);
}
if (defined('PHPCS_DEFAULT_ERROR_SEV') === false) {
define('PHPCS_DEFAULT_ERROR_SEV', 5);
}
if (defined('PHPCS_DEFAULT_WARN_SEV') === false) {
define('PHPCS_DEFAULT_WARN_SEV', 5);
}
// Set default CLI object in case someone is running us
// without using the command line script.
$this->cli = new PHP_CodeSniffer_CLI();
$this->cli->errorSeverity = PHPCS_DEFAULT_ERROR_SEV;
$this->cli->warningSeverity = PHPCS_DEFAULT_WARN_SEV;
$this->cli->dieOnUnknownArg = false;
$this->reporting = new PHP_CodeSniffer_Reporting();
}//end __construct()
/**
* Autoload static method for loading classes and interfaces.
*
* @param string $className The name of the class or interface.
*
* @return void
*/
public static function autoload($className)
{
if (substr($className, 0, 4) === 'PHP_') {
$newClassName = substr($className, 4);
} else {
$newClassName = $className;
}
$path = str_replace(array('_', '\\'), '/', $newClassName).'.php';
if (is_file(dirname(__FILE__).'/'.$path) === true) {
// Check standard file locations based on class name.
include dirname(__FILE__).'/'.$path;
} else if (is_file(dirname(__FILE__).'/CodeSniffer/Standards/'.$path) === true) {
// Check for included sniffs.
include dirname(__FILE__).'/CodeSniffer/Standards/'.$path;
} else {
// Check standard file locations based on the loaded rulesets.
foreach (self::$rulesetDirs as $rulesetDir) {
if (is_file(dirname($rulesetDir).'/'.$path) === true) {
include dirname($rulesetDir).'/'.$path;
return;
}
}
// Everything else.
@include $path;
}
}//end autoload()
/**
* Sets an array of file extensions that we will allow checking of.
*
* If the extension is one of the defaults, a specific tokenizer
* will be used. Otherwise, the PHP tokenizer will be used for
* all extensions passed.
*
* @param array $extensions An array of file extensions.
*
* @return void
*/
public function setAllowedFileExtensions(array $extensions)
{
$newExtensions = array();
foreach ($extensions as $ext) {
if (isset($this->allowedFileExtensions[$ext]) === true) {
$newExtensions[$ext] = $this->allowedFileExtensions[$ext];
} else {
$newExtensions[$ext] = 'PHP';
}
}
$this->allowedFileExtensions = $newExtensions;
}//end setAllowedFileExtensions()
/**
* Sets an array of ignore patterns that we use to skip files and folders.
*
* Patterns are not case sensitive.
*
* @param array $patterns An array of ignore patterns. The pattern is the key
* and the value is either "absolute" or "relative",
* depending on how the pattern should be applied to a
* file path.
*
* @return void
*/
public function setIgnorePatterns(array $patterns)
{
$this->ignorePatterns = $patterns;
}//end setIgnorePatterns()
/**
* Gets the array of ignore patterns.
*
* Optionally takes a listener to get ignore patterns specified
* for that sniff only.
*
* @param string $listener The listener to get patterns for. If NULL, all
* patterns are returned.
*
* @return array
*/
public function getIgnorePatterns($listener=null)
{
if ($listener === null) {
return $this->ignorePatterns;
}
if (isset($this->ignorePatterns[$listener]) === true) {
return $this->ignorePatterns[$listener];
}
return array();
}//end getIgnorePatterns()
/**
* Sets the internal CLI object.
*
* @param object $cli The CLI object controlling the run.
*
* @return void
*/
public function setCli($cli)
{
$this->cli = $cli;
}//end setCli()
/**
* Processes the files/directories that PHP_CodeSniffer was constructed with.
*
* @param string|array $files The files and directories to process. For
* directories, each sub directory will also
* be traversed for source files.
* @param string|array $standards The set of code sniffs we are testing
* against.
* @param array $restrictions The sniff names to restrict the allowed
* listeners to.
* @param boolean $local If true, don't recurse into directories.
*
* @return void
* @throws PHP_CodeSniffer_Exception If files or standard are invalid.
*/
public function process($files, $standards, array $restrictions=array(), $local=false)
{
if (is_array($files) === false) {
$files = array($files);
}
if (is_array($standards) === false) {
$standards = array($standards);
}
// Reset the members.
$this->listeners = array();
$this->sniffs = array();
$this->ruleset = array();
$this->_tokenListeners = array();
self::$rulesetDirs = array();
// Ensure this option is enabled or else line endings will not always
// be detected properly for files created on a Mac with the /r line ending.
ini_set('auto_detect_line_endings', true);
$sniffs = array();
foreach ($standards as $standard) {
$installed = $this->getInstalledStandardPath($standard);
if ($installed !== null) {
$standard = $installed;
}
if (PHP_CODESNIFFER_VERBOSITY === 1) {
$ruleset = simplexml_load_file($standard);
if ($ruleset !== false) {
$standardName = (string) $ruleset['name'];
}
echo "Registering sniffs in the $standardName standard... ";
if (count($standards) > 1 || PHP_CODESNIFFER_VERBOSITY > 2) {
echo PHP_EOL;
}
}
$sniffs = array_merge($sniffs, $this->processRuleset($standard));
}//end foreach
$this->registerSniffs($sniffs, $restrictions);
$this->populateTokenListeners();
if (PHP_CODESNIFFER_VERBOSITY === 1) {
$numSniffs = count($this->sniffs);
echo "DONE ($numSniffs sniffs registered)".PHP_EOL;
}
// The SVN pre-commit calls process() to init the sniffs
// and ruleset so there may not be any files to process.
// But this has to come after that initial setup.
if (empty($files) === true) {
return;
}
$cliValues = $this->cli->getCommandLineValues();
$showProgress = $cliValues['showProgress'];
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'Creating file list... ';
}
$todo = $this->getFilesToProcess($files, $local);
$numFiles = count($todo);
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo "DONE ($numFiles files in queue)".PHP_EOL;
}
$numProcessed = 0;
$dots = 0;
$maxLength = strlen($numFiles);
$lastDir = '';
foreach ($todo as $file) {
$this->file = $file;
$currDir = dirname($file);
if ($lastDir !== $currDir) {
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'Changing into directory '.$currDir.PHP_EOL;
}
$lastDir = $currDir;
}
$phpcsFile = $this->processFile($file);
$numProcessed++;
if (PHP_CODESNIFFER_VERBOSITY > 0
|| PHP_CODESNIFFER_INTERACTIVE === true
|| $showProgress === false
) {
continue;
}
// Show progress information.
if ($phpcsFile === null) {
echo 'S';
} else {
$errors = $phpcsFile->getErrorCount();
$warnings = $phpcsFile->getWarningCount();
if ($errors > 0) {
echo 'E';
} else if ($warnings > 0) {
echo 'W';
} else {
echo '.';
}
}
$dots++;
if ($dots === 60) {
$padding = ($maxLength - strlen($numProcessed));
echo str_repeat(' ', $padding);
echo " $numProcessed / $numFiles".PHP_EOL;
$dots = 0;
}
}//end foreach
if (PHP_CODESNIFFER_VERBOSITY === 0
&& PHP_CODESNIFFER_INTERACTIVE === false
&& $showProgress === true
) {
echo PHP_EOL.PHP_EOL;
}
}//end process()
/**
* Processes a single ruleset and returns a list of the sniffs it represents.
*
* Rules founds within the ruleset are processed immediately, but sniff classes
* are not registered by this method.
*
* @param string $rulesetPath The path to a ruleset XML file.
* @param int $depth How many nested processing steps we are in. This
* is only used for debug output.
*
* @return array
* @throws PHP_CodeSniffer_Exception If the ruleset path is invalid.
*/
public function processRuleset($rulesetPath, $depth=0)
{
$rulesetPath = realpath($rulesetPath);
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "Processing ruleset $rulesetPath".PHP_EOL;
}
$ruleset = simplexml_load_file($rulesetPath);
if ($ruleset === false) {
throw new PHP_CodeSniffer_Exception("Ruleset $rulesetPath is not valid");
}
$ownSniffs = array();
$includedSniffs = array();
$excludedSniffs = array();
$rulesetDir = dirname($rulesetPath);
self::$rulesetDirs[] = $rulesetDir;
if (is_dir($rulesetDir.'/Sniffs') === true) {
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\tAdding sniff files from \".../".basename($rulesetDir)."/Sniffs/\" directory".PHP_EOL;
}
$ownSniffs = $this->_expandSniffDirectory($rulesetDir.'/Sniffs', $depth);
}
foreach ($ruleset->rule as $rule) {
if (isset($rule['ref']) === false) {
continue;
}
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\tProcessing rule \"".$rule['ref'].'"'.PHP_EOL;
}
$includedSniffs = array_merge(
$includedSniffs,
$this->_expandRulesetReference($rule['ref'], $rulesetDir, $depth)
);
if (isset($rule->exclude) === true) {
foreach ($rule->exclude as $exclude) {
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\tExcluding rule \"".$exclude['name'].'"'.PHP_EOL;
}
$excludedSniffs = array_merge(
$excludedSniffs,
$this->_expandRulesetReference($exclude['name'], $rulesetDir, ($depth + 1))
);
}
}
$this->_processRule($rule, $depth);
}//end foreach
// Process custom ignore pattern rules.
foreach ($ruleset->{'exclude-pattern'} as $pattern) {
if (isset($pattern['type']) === false) {
$pattern['type'] = 'absolute';
}
$this->ignorePatterns[(string) $pattern] = (string) $pattern['type'];
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t=> added global ".(string) $pattern['type'].' ignore pattern: '.(string) $pattern.PHP_EOL;
}
}
$includedSniffs = array_unique(array_merge($ownSniffs, $includedSniffs));
$excludedSniffs = array_unique($excludedSniffs);
if (PHP_CODESNIFFER_VERBOSITY > 1) {
$included = count($includedSniffs);
$excluded = count($excludedSniffs);
echo str_repeat("\t", $depth);
echo "=> Ruleset processing complete; included $included sniffs and excluded $excluded".PHP_EOL;
}
// Merge our own sniff list with our externally included
// sniff list, but filter out any excluded sniffs.
$files = array();
foreach ($includedSniffs as $sniff) {
if (in_array($sniff, $excludedSniffs) === true) {
continue;
} else {
$files[] = realpath($sniff);
}
}
return $files;
}//end processRuleset()
/**
* Expands a directory into a list of sniff files within.
*
* @param string $directory The path to a directory.
* @param int $depth How many nested processing steps we are in. This
* is only used for debug output.
*
* @return array
*/
private function _expandSniffDirectory($directory, $depth=0)
{
$sniffs = array();
$di = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
foreach ($di as $file) {
$fileName = $file->getFilename();
// Skip hidden files.
if (substr($fileName, 0, 1) === '.') {
continue;
}
// We are only interested in PHP and sniff files.
$fileParts = explode('.', $fileName);
if (array_pop($fileParts) !== 'php') {
continue;
}
$basename = basename($fileName, '.php');
if (substr($basename, -5) !== 'Sniff') {
continue;
}
$path = $file->getPathname();
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> $path".PHP_EOL;
}
$sniffs[] = $path;
}//end foreach
return $sniffs;
}//end _expandSniffDirectory()
/**
* Expands a ruleset reference into a list of sniff files.
*
* @param string $ref The reference from the ruleset XML file.
* @param string $rulesetDir The directory of the ruleset XML file, used to
* evaluate relative paths.
* @param int $depth How many nested processing steps we are in. This
* is only used for debug output.
*
* @return array
* @throws PHP_CodeSniffer_Exception If the reference is invalid.
*/
private function _expandRulesetReference($ref, $rulesetDir, $depth=0)
{
// Ignore internal sniffs codes as they are used to only
// hide and change internal messages.
if (substr($ref, 0, 9) === 'Internal.') {
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t* ignoring internal sniff code *".PHP_EOL;
}
return array();
}
// As sniffs can't begin with a full stop, assume references in
// this format are relative paths and attempt to convert them
// to absolute paths. If this fails, let the reference run through
// the normal checks and have it fail as normal.
if (substr($ref, 0, 1) === '.') {
$realpath = realpath($rulesetDir.'/'.$ref);
if ($realpath !== false) {
$ref = $realpath;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> $ref".PHP_EOL;
}
}
}
if (is_dir($ref) === false && is_file($ref) === false) {
// See if this is a whole standard being referenced.
$path = realpath(dirname(__FILE__).'/CodeSniffer/Standards/'.$ref);
if (is_dir($path) === true) {
$ref = $path;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> $ref".PHP_EOL;
}
} else {
// Work out the sniff path.
$parts = explode('.', $ref);
if (count($parts) === 1) {
// A whole standard?
$path = '';
} else if (count($parts) === 2) {
// A directory of sniffs?
$path = '/Sniffs/'.$parts[1];
} else {
// A single sniff?
$path = '/Sniffs/'.$parts[1].'/'.$parts[2].'Sniff.php';
}
$newRef = realpath(dirname(__FILE__).'/CodeSniffer/Standards/'.$parts[0].$path);
if ($newRef === false) {
// The sniff is not locally installed, so check if it is being
// referenced as a remote sniff outside the install. We do this
// by looking through all directories where we have found ruleset
// files before, looking for ones for this particular standard,
// and seeing if it is in there.
foreach (self::$rulesetDirs as $dir) {
if (basename($dir) !== $parts[0]) {
continue;
}
$newRef = realpath($dir.$path);
if ($newRef !== false) {
$ref = $newRef;
}
}
} else {
$ref = $newRef;
}
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> $ref".PHP_EOL;
}
}
}//end if
if (is_dir($ref) === true) {
if (is_file($ref.'/ruleset.xml') === true) {
// We are referencing an external coding standard.
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t* rule is referencing a standard using directory name; processing *".PHP_EOL;
}
return $this->processRuleset($ref.'/ruleset.xml', ($depth + 2));
} else {
// We are referencing a whole directory of sniffs.
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t* rule is referencing a directory of sniffs *".PHP_EOL;
echo str_repeat("\t", $depth);
echo "\t\tAdding sniff files from directory".PHP_EOL;
}
return $this->_expandSniffDirectory($ref, ($depth + 1));
}
} else {
if (is_file($ref) === false) {
$error = "Referenced sniff \"$ref\" does not exist";
throw new PHP_CodeSniffer_Exception($error);
}
if (substr($ref, -9) === 'Sniff.php') {
// A single sniff.
return array($ref);
} else {
// Assume an external ruleset.xml file.
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t* rule is referencing a standard using ruleset path; processing *".PHP_EOL;
}
return $this->processRuleset($ref, ($depth + 2));
}
}//end if
}//end _expandRulesetReference()
/**
* Processes a rule from a ruleset XML file, overriding built-in defaults.
*
* @param SimpleXMLElement $rule The rule object from a ruleset XML file.
* @param int $depth How many nested processing steps we are in.
* This is only used for debug output.
*
* @return void
*/
private function _processRule($rule, $depth=0)
{
$code = (string) $rule['ref'];
// Custom severity.
if (isset($rule->severity) === true) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = array();
}
$this->ruleset[$code]['severity'] = (int) $rule->severity;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> severity set to ".(int) $rule->severity.PHP_EOL;
}
}
// Custom message type.
if (isset($rule->type) === true) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = array();
}
$this->ruleset[$code]['type'] = (string) $rule->type;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> message type set to ".(string) $rule->type.PHP_EOL;
}
}
// Custom message.
if (isset($rule->message) === true) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = array();
}
$this->ruleset[$code]['message'] = (string) $rule->message;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> message set to ".(string) $rule->message.PHP_EOL;
}
}
// Custom properties.
if (isset($rule->properties) === true) {
foreach ($rule->properties->property as $prop) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = array(
'properties' => array(),
);
} else if (isset($this->ruleset[$code]['properties']) === false) {
$this->ruleset[$code]['properties'] = array();
}
$name = (string) $prop['name'];
if (isset($prop['type']) === true
&& (string) $prop['type'] === 'array'
) {
$value = (string) $prop['value'];
$this->ruleset[$code]['properties'][$name] = explode(',', $value);
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> array property \"$name\" set to \"$value\"".PHP_EOL;
}
} else {
$this->ruleset[$code]['properties'][$name] = (string) $prop['value'];
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> property \"$name\" set to \"".(string) $prop['value'].'"'.PHP_EOL;
}
}
}//end foreach
}//end if
// Ignore patterns.
foreach ($rule->{'exclude-pattern'} as $pattern) {
if (isset($this->ignorePatterns[$code]) === false) {
$this->ignorePatterns[$code] = array();
}
if (isset($pattern['type']) === false) {
$pattern['type'] = 'absolute';
}
$this->ignorePatterns[$code][(string) $pattern] = (string) $pattern['type'];
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> added sniff-specific ".(string) $pattern['type'].' ignore pattern: '.(string) $pattern.PHP_EOL;
}
}
}//end _processRule()
/**
* Loads and stores sniffs objects used for sniffing files.
*
* @param array $files Paths to the sniff files to register.
* @param array $restrictions The sniff class names to restrict the allowed
* listeners to.
*
* @return void
*/
public function registerSniffs($files, $restrictions)
{
$listeners = array();
foreach ($files as $file) {
// Work out where the position of /StandardName/Sniffs/... is
// so we can determine what the class will be called.
$sniffPos = strrpos($file, DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR);
if ($sniffPos === false) {
continue;
}
$slashPos = strrpos(substr($file, 0, $sniffPos), DIRECTORY_SEPARATOR);
if ($slashPos === false) {
continue;
}
$className = substr($file, ($slashPos + 1));
$className = substr($className, 0, -4);
$className = str_replace(DIRECTORY_SEPARATOR, '_', $className);
include_once $file;
// Support the use of PHP namespaces. If the class name we included
// contains namespace separators instead of underscores, use this as the
// class name from now on.
$classNameNS = str_replace('_', '\\', $className);
if (class_exists($classNameNS, false) === true) {
$className = $classNameNS;
}
// If they have specified a list of sniffs to restrict to, check
// to see if this sniff is allowed.
if (empty($restrictions) === false
&& in_array(strtolower($className), $restrictions) === false
) {
continue;
}
$listeners[$className] = $className;
if (PHP_CODESNIFFER_VERBOSITY > 2) {
echo "Registered $className".PHP_EOL;
}
}//end foreach
$this->sniffs = $listeners;
}//end registerSniffs()
/**
* Populates the array of PHP_CodeSniffer_Sniff's for this file.
*
* @return void
* @throws PHP_CodeSniffer_Exception If sniff registration fails.
*/
public function populateTokenListeners()
{
// Construct a list of listeners indexed by token being listened for.
$this->_tokenListeners = array();
foreach ($this->sniffs as $listenerClass) {
// Work out the internal code for this sniff. Detect usage of namespace
// separators instead of underscores to support PHP namespaces.
if (strstr($listenerClass, '\\') === false) {
$parts = explode('_', $listenerClass);
} else {
$parts = explode('\\', $listenerClass);
}
$code = $parts[0].'.'.$parts[2].'.'.$parts[3];
$code = substr($code, 0, -5);
$this->listeners[$listenerClass] = new $listenerClass();
// Set custom properties.
if (isset($this->ruleset[$code]['properties']) === true) {
foreach ($this->ruleset[$code]['properties'] as $name => $value) {
$this->setSniffProperty($listenerClass, $name, $value);
}
}
$tokenizers = array('PHP');
$vars = get_class_vars($listenerClass);
if (isset($vars['supportedTokenizers']) === true) {
$tokenizers = $vars['supportedTokenizers'];
}
$tokens = $this->listeners[$listenerClass]->register();
if (is_array($tokens) === false) {
$msg = "Sniff $listenerClass register() method must return an array";
throw new PHP_CodeSniffer_Exception($msg);
}
foreach ($tokens as $token) {
if (isset($this->_tokenListeners[$token]) === false) {
$this->_tokenListeners[$token] = array();
}
if (in_array($this->listeners[$listenerClass], $this->_tokenListeners[$token], true) === false) {
$this->_tokenListeners[$token][] = array(
'listener' => $this->listeners[$listenerClass],
'class' => $listenerClass,
'tokenizers' => $tokenizers,
);
}
}
}//end foreach
}//end populateTokenListeners()
/**
* Set a single property for a sniff.
*
* @param string $listenerClass The class name of the sniff.
* @param string $name The name of the property to change.
* @param string $value The new value of the property.
*
* @return void
*/
public function setSniffProperty($listenerClass, $name, $value)
{
// Setting a property for a sniff we are not using.
if (isset($this->listeners[$listenerClass]) === false) {
return;
}
$name = trim($name);
if (is_string($value) === true) {
$value = trim($value);
}
// Special case for booleans.
if ($value === 'true') {
$value = true;
} else if ($value === 'false') {
$value = false;
}
$this->listeners[$listenerClass]->$name = $value;
}//end setSniffProperty()
/**
* Get a list of files that will be processed.
*
* If passed directories, this method will find all files within them.
* The method will also perform file extension and ignore pattern filtering.
*
* @param string $paths A list of file or directory paths to process.
* @param boolean $local If true, only process 1 level of files in directories
*
* @return array
* @throws Exception If there was an error opening a directory.
* @see shouldProcessFile()
*/
public function getFilesToProcess($paths, $local=false)
{
$files = array();
foreach ($paths as $path) {
if (is_dir($path) === true) {
if ($local === true) {
$di = new DirectoryIterator($path);
} else {
$di = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
}
foreach ($di as $file) {
// Check if the file exists after all symlinks are resolved.
$filePath = realpath($file->getPathname());
if ($filePath === false) {
continue;
}
if (is_dir($filePath) === true) {
continue;
}
if ($this->shouldProcessFile($file->getPathname(), $path) === false) {
continue;
}
$files[] = $file->getPathname();
}//end foreach
} else {
if ($this->shouldIgnoreFile($path, dirname($path)) === true) {
continue;
}
$files[] = $path;
}//end if
}//end foreach
return $files;
}//end getFilesToProcess()
/**
* Checks filtering rules to see if a file should be checked.
*
* Checks both file extension filters and path ignore filters.
*
* @param string $path The path to the file being checked.
* @param string $basedir The directory to use for relative path checks.
*
* @return bool
*/
public function shouldProcessFile($path, $basedir)
{
// Check that the file's extension is one we are checking.
// We are strict about checking the extension and we don't
// let files through with no extension or that start with a dot.
$fileName = basename($path);
$fileParts = explode('.', $fileName);
if ($fileParts[0] === $fileName || $fileParts[0] === '') {
return false;
}
// Checking multi-part file extensions, so need to create a
// complete extension list and make sure one is allowed.
$extensions = array();
array_shift($fileParts);
foreach ($fileParts as $part) {
$extensions[implode('.', $fileParts)] = 1;
array_shift($fileParts);
}
$matches = array_intersect_key($extensions, $this->allowedFileExtensions);
if (empty($matches) === true) {
return false;
}
// If the file's path matches one of our ignore patterns, skip it.
if ($this->shouldIgnoreFile($path, $basedir) === true) {
return false;
}
return true;
}//end shouldProcessFile()
/**
* Checks filtering rules to see if a file should be ignored.
*
* @param string $path The path to the file being checked.
* @param string $basedir The directory to use for relative path checks.
*
* @return bool
*/
public function shouldIgnoreFile($path, $basedir)
{
$relativePath = $path;
if (strpos($path, $basedir) === 0) {
// The +1 cuts off the directory separator as well.
$relativePath = substr($path, (strlen($basedir) + 1));
}
foreach ($this->ignorePatterns as $pattern => $type) {
if (is_array($pattern) === true) {
// A sniff specific ignore pattern.
continue;
}
// Maintains backwards compatibility in case the ignore pattern does
// not have a relative/absolute value.
if (is_int($pattern) === true) {
$pattern = $type;
$type = 'absolute';
}
$replacements = array(
'\\,' => ',',
'*' => '.*',
);
// We assume a / directory separator, as do the exclude rules
// most developers write, so we need a special case for any system
// that is different.
if (DIRECTORY_SEPARATOR === '\\') {
$replacements['/'] = '\\\\';
}
$pattern = strtr($pattern, $replacements);
if ($type === 'relative') {
$testPath = $relativePath;
} else {
$testPath = $path;
}
if (preg_match("|{$pattern}|i", $testPath) === 1) {
return true;
}
}//end foreach
return false;
}//end shouldIgnoreFile()
/**
* Run the code sniffs over a single given file.
*
* Processes the file and runs the PHP_CodeSniffer sniffs to verify that it
* conforms with the standard. Returns the processed file object, or NULL
* if no file was processed due to error.
*
* @param string $file The file to process.
* @param string $contents The contents to parse. If NULL, the content
* is taken from the file system.
*
* @return PHP_CodeSniffer_File
* @throws PHP_CodeSniffer_Exception If the file could not be processed.
* @see _processFile()
*/
public function processFile($file, $contents=null)
{
if ($contents === null && file_exists($file) === false) {
throw new PHP_CodeSniffer_Exception("Source file $file does not exist");
}
$filePath = realpath($file);
if ($filePath === false) {
$filePath = $file;
}
// Before we go and spend time tokenizing this file, just check
// to see if there is a tag up top to indicate that the whole
// file should be ignored. It must be on one of the first two lines.
$firstContent = $contents;
if ($contents === null && is_readable($filePath) === true) {
$handle = fopen($filePath, 'r');
if ($handle !== false) {
$firstContent = fgets($handle);
$firstContent .= fgets($handle);
fclose($handle);
}
}
if (strpos($firstContent, '@codingStandardsIgnoreFile') !== false) {
// We are ignoring the whole file.
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'Ignoring '.basename($filePath).PHP_EOL;
}
return null;
}
try {
$phpcsFile = $this->_processFile($file, $contents);
} catch (Exception $e) {
$trace = $e->getTrace();
$filename = $trace[0]['args'][0];
if (is_object($filename) === true
&& get_class($filename) === 'PHP_CodeSniffer_File'
) {
$filename = $filename->getFilename();
} else if (is_numeric($filename) === true) {
// See if we can find the PHP_CodeSniffer_File object.
foreach ($trace as $data) {
if (isset($data['args'][0]) === true
&& ($data['args'][0] instanceof PHP_CodeSniffer_File) === true
) {
$filename = $data['args'][0]->getFilename();
}
}
} else if (is_string($filename) === false) {
$filename = (string) $filename;
}
$error = 'An error occurred during processing; checking has been aborted. The error message was: '.$e->getMessage();
$phpcsFile = new PHP_CodeSniffer_File(
$filename,
$this->_tokenListeners,
$this->allowedFileExtensions,
$this->ruleset,
$this
);
$phpcsFile->addError($error, null);
}//end try
$cliValues = $this->cli->getCommandLineValues();
if (PHP_CODESNIFFER_INTERACTIVE === false) {
// Cache the report data for this file so we can unset it to save memory.
$this->reporting->cacheFileReport($phpcsFile, $cliValues);
return $phpcsFile;
}
/*
Running interactively.
Print the error report for the current file and then wait for user input.
*/
// Get current violations and then clear the list to make sure
// we only print violations for a single file each time.
$numErrors = null;
while ($numErrors !== 0) {
$numErrors = ($phpcsFile->getErrorCount() + $phpcsFile->getWarningCount());
if ($numErrors === 0) {
continue;
}
$reportClass = $this->reporting->factory('full');
$reportData = $this->reporting->prepareFileReport($phpcsFile);
$reportClass->generateFileReport($reportData, $cliValues['showSources'], $cliValues['reportWidth']);
echo '<ENTER> to recheck, [s] to skip or [q] to quit : ';
$input = fgets(STDIN);
$input = trim($input);
switch ($input) {
case 's':
break(2);
case 'q':
exit(0);
break;
default:
// Repopulate the sniffs because some of them save their state
// and only clear it when the file changes, but we are rechecking
// the same file.
$this->populateTokenListeners();
$phpcsFile = $this->_processFile($file, $contents);
break;
}
}//end while
return $phpcsFile;
}//end processFile()
/**
* Process the sniffs for a single file.
*
* Does raw processing only. No interactive support or error checking.
*
* @param string $file The file to process.
* @param string $contents The contents to parse. If NULL, the content
* is taken from the file system.
*
* @return PHP_CodeSniffer_File
* @see processFile()
*/
private function _processFile($file, $contents)
{
if (PHP_CODESNIFFER_VERBOSITY > 0) {
$startTime = time();
echo 'Processing '.basename($file).' ';
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo PHP_EOL;
}
}
$phpcsFile = new PHP_CodeSniffer_File(
$file,
$this->_tokenListeners,
$this->allowedFileExtensions,
$this->ruleset,
$this
);
$phpcsFile->start($contents);
$phpcsFile->cleanUp();
if (PHP_CODESNIFFER_VERBOSITY > 0) {
$timeTaken = (time() - $startTime);
if ($timeTaken === 0) {
echo 'DONE in < 1 second';
} else if ($timeTaken === 1) {
echo 'DONE in 1 second';
} else {
echo "DONE in $timeTaken seconds";
}
$errors = $phpcsFile->getErrorCount();
$warnings = $phpcsFile->getWarningCount();
echo " ($errors errors, $warnings warnings)".PHP_EOL;
}
return $phpcsFile;
}//end _processFile()
/**
* Generates documentation for a coding standard.
*
* @param string $standard The standard to generate docs for
* @param array $sniffs A list of sniffs to limit the docs to.
* @param string $generator The name of the generator class to use.
*
* @return void
*/
public function generateDocs($standard, array $sniffs=array(), $generator='Text')
{
if (class_exists('PHP_CodeSniffer_DocGenerators_'.$generator, true) === false) {
throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_DocGenerators_'.$generator.' not found');
}
$class = "PHP_CodeSniffer_DocGenerators_$generator";
$generator = new $class($standard, $sniffs);
$generator->generate();
}//end generateDocs()
/**
* Gets the array of PHP_CodeSniffer_Sniff's.
*
* @return array(PHP_CodeSniffer_Sniff)
*/
public function getSniffs()
{
return $this->listeners;
}//end getSniffs()
/**
* Gets the array of PHP_CodeSniffer_Sniff's indexed by token type.
*
* @return array()
*/
public function getTokenSniffs()
{
return $this->_tokenListeners;
}//end getTokenSniffs()
/**
* Takes a token produced from <code>token_get_all()</code> and produces a
* more uniform token.
*
* Note that this method also resolves T_STRING tokens into more discrete
* types, therefore there is no need to call resolveTstringToken()
*
* @param string|array $token The token to convert.
*
* @return array The new token.
*/
public static function standardiseToken($token)
{
if (is_array($token) === false) {
if (isset(self::$_resolveTokenCache[$token]) === true) {
$newToken = self::$_resolveTokenCache[$token];
} else {
$newToken = self::resolveSimpleToken($token);
}
} else {
switch ($token[0]) {
case T_STRING:
// Some T_STRING tokens can be more specific.
$tokenType = strtolower($token[1]);
if (isset(self::$_resolveTokenCache[$tokenType]) === true) {
$newToken = self::$_resolveTokenCache[$tokenType];
} else {
$newToken = self::resolveTstringToken($tokenType);
}
break;
case T_CURLY_OPEN:
$newToken = array(
'code' => T_OPEN_CURLY_BRACKET,
'type' => 'T_OPEN_CURLY_BRACKET',
);
break;
default:
$newToken = array(
'code' => $token[0],
'type' => token_name($token[0]),
);
break;
}//end switch
$newToken['content'] = $token[1];
}//end if
return $newToken;
}//end standardiseToken()
/**
* Converts T_STRING tokens into more usable token names.
*
* The token should be produced using the token_get_all() function.
* Currently, not all T_STRING tokens are converted.
*
* @param string $token The T_STRING token to convert as constructed
* by token_get_all().
*
* @return array The new token.
*/
public static function resolveTstringToken($token)
{
$newToken = array();
switch ($token) {
case 'false':
$newToken['type'] = 'T_FALSE';
break;
case 'true':
$newToken['type'] = 'T_TRUE';
break;
case 'null':
$newToken['type'] = 'T_NULL';
break;
case 'self':
$newToken['type'] = 'T_SELF';
break;
case 'parent':
$newToken['type'] = 'T_PARENT';
break;
default:
$newToken['type'] = 'T_STRING';
break;
}
$newToken['code'] = constant($newToken['type']);
self::$_resolveTokenCache[$token] = $newToken;
return $newToken;
}//end resolveTstringToken()
/**
* Converts simple tokens into a format that conforms to complex tokens
* produced by token_get_all().
*
* Simple tokens are tokens that are not in array form when produced from
* token_get_all().
*
* @param string $token The simple token to convert.
*
* @return array The new token in array format.
*/
public static function resolveSimpleToken($token)
{
$newToken = array();
switch ($token) {
case '{':
$newToken['type'] = 'T_OPEN_CURLY_BRACKET';
break;
case '}':
$newToken['type'] = 'T_CLOSE_CURLY_BRACKET';
break;
case '[':
$newToken['type'] = 'T_OPEN_SQUARE_BRACKET';
break;
case ']':
$newToken['type'] = 'T_CLOSE_SQUARE_BRACKET';
break;
case '(':
$newToken['type'] = 'T_OPEN_PARENTHESIS';
break;
case ')':
$newToken['type'] = 'T_CLOSE_PARENTHESIS';
break;
case ':':
$newToken['type'] = 'T_COLON';
break;
case '.':
$newToken['type'] = 'T_STRING_CONCAT';
break;
case '?':
$newToken['type'] = 'T_INLINE_THEN';
break;
case ';':
$newToken['type'] = 'T_SEMICOLON';
break;
case '=':
$newToken['type'] = 'T_EQUAL';
break;
case '*':
$newToken['type'] = 'T_MULTIPLY';
break;
case '/':
$newToken['type'] = 'T_DIVIDE';
break;
case '+':
$newToken['type'] = 'T_PLUS';
break;
case '-':
$newToken['type'] = 'T_MINUS';
break;
case '%':
$newToken['type'] = 'T_MODULUS';
break;
case '^':
$newToken['type'] = 'T_POWER';
break;
case '&':
$newToken['type'] = 'T_BITWISE_AND';
break;
case '|':
$newToken['type'] = 'T_BITWISE_OR';
break;
case '<':
$newToken['type'] = 'T_LESS_THAN';
break;
case '>':
$newToken['type'] = 'T_GREATER_THAN';
break;
case '!':
$newToken['type'] = 'T_BOOLEAN_NOT';
break;
case ',':
$newToken['type'] = 'T_COMMA';
break;
case '@':
$newToken['type'] = 'T_ASPERAND';
break;
case '$':
$newToken['type'] = 'T_DOLLAR';
break;
case '`':
$newToken['type'] = 'T_BACKTICK';
break;
default:
$newToken['type'] = 'T_NONE';
break;
}//end switch
$newToken['code'] = constant($newToken['type']);
$newToken['content'] = $token;
self::$_resolveTokenCache[$token] = $newToken;
return $newToken;
}//end resolveSimpleToken()
/**
* Returns true if the specified string is in the camel caps format.
*
* @param string $string The string the verify.
* @param boolean $classFormat If true, check to see if the string is in the
* class format. Class format strings must start
* with a capital letter and contain no
* underscores.
* @param boolean $public If true, the first character in the string
* must be an a-z character. If false, the
* character must be an underscore. This
* argument is only applicable if $classFormat
* is false.
* @param boolean $strict If true, the string must not have two capital
* letters next to each other. If false, a
* relaxed camel caps policy is used to allow
* for acronyms.
*
* @return boolean
*/
public static function isCamelCaps(
$string,
$classFormat=false,
$public=true,
$strict=true
) {
// Check the first character first.
if ($classFormat === false) {
if ($public === false) {
$legalFirstChar = '[_][a-z]';
} else {
$legalFirstChar = '[a-z]';
}
} else {
$legalFirstChar = '[A-Z]';
}
if (preg_match("|^$legalFirstChar|", $string) === 0) {
return false;
}
// Check that the name only contains legal characters.
$legalChars = 'a-zA-Z0-9';
if (preg_match("|[^$legalChars]|", substr($string, 1)) > 0) {
return false;
}
if ($strict === true) {
// Check that there are not two capital letters next to each other.
$length = strlen($string);
$lastCharWasCaps = $classFormat;
for ($i = 1; $i < $length; $i++) {
$ascii = ord($string{$i});
if ($ascii >= 48 && $ascii <= 57) {
// The character is a number, so it cant be a capital.
$isCaps = false;
} else {
if (strtoupper($string{$i}) === $string{$i}) {
$isCaps = true;
} else {
$isCaps = false;
}
}
if ($isCaps === true && $lastCharWasCaps === true) {
return false;
}
$lastCharWasCaps = $isCaps;
}
}//end if
return true;
}//end isCamelCaps()
/**
* Returns true if the specified string is in the underscore caps format.
*
* @param string $string The string to verify.
*
* @return boolean
*/
public static function isUnderscoreName($string)
{
// If there are space in the name, it can't be valid.
if (strpos($string, ' ') !== false) {
return false;
}
$validName = true;
$nameBits = explode('_', $string);
if (preg_match('|^[A-Z]|', $string) === 0) {
// Name does not begin with a capital letter.
$validName = false;
} else {
foreach ($nameBits as $bit) {
if ($bit === '') {
continue;
}
if ($bit{0} !== strtoupper($bit{0})) {
$validName = false;
break;
}
}
}
return $validName;
}//end isUnderscoreName()
/**
* Returns a valid variable type for param/var tag.
*
* If type is not one of the standard type, it must be a custom type.
* Returns the correct type name suggestion if type name is invalid.
*
* @param string $varType The variable type to process.
*
* @return string
*/
public static function suggestType($varType)
{
if ($varType === '') {
return '';
}
if (in_array($varType, self::$allowedTypes) === true) {
return $varType;
} else {
$lowerVarType = strtolower($varType);
switch ($lowerVarType) {
case 'bool':
return 'boolean';
case 'double':
case 'real':
return 'float';
case 'int':
return 'integer';
case 'array()':
return 'array';
}//end switch
if (strpos($lowerVarType, 'array(') !== false) {
// Valid array declaration:
// array, array(type), array(type1 => type2).
$matches = array();
$pattern = '/^array\(\s*([^\s^=^>]*)(\s*=>\s*(.*))?\s*\)/i';
if (preg_match($pattern, $varType, $matches) !== 0) {
$type1 = '';
if (isset($matches[1]) === true) {
$type1 = $matches[1];
}
$type2 = '';
if (isset($matches[3]) === true) {
$type2 = $matches[3];
}
$type1 = self::suggestType($type1);
$type2 = self::suggestType($type2);
if ($type2 !== '') {
$type2 = ' => '.$type2;
}
return "array($type1$type2)";
} else {
return 'array';
}//end if
} else if (in_array($lowerVarType, self::$allowedTypes) === true) {
// A valid type, but not lower cased.
return $lowerVarType;
} else {
// Must be a custom type name.
return $varType;
}//end if
}//end if
}//end suggestType()
/**
* Get a list of all coding standards installed.
*
* Coding standards are directories located in the
* CodeSniffer/Standards directory. Valid coding standards
* include a Sniffs subdirectory.
*
* @param boolean $includeGeneric If true, the special "Generic"
* coding standard will be included
* if installed.
* @param string $standardsDir A specific directory to look for standards
* in. If not specified, PHP_CodeSniffer will
* look in its default location.
*
* @return array
* @see isInstalledStandard()
*/
public static function getInstalledStandards(
$includeGeneric=false,
$standardsDir=''
) {
$installedStandards = array();
if ($standardsDir === '') {
$standardsDir = dirname(__FILE__).'/CodeSniffer/Standards';
}
$di = new DirectoryIterator($standardsDir);
foreach ($di as $file) {
if ($file->isDir() === true && $file->isDot() === false) {
$filename = $file->getFilename();
// Ignore the special "Generic" standard.
if ($includeGeneric === false && $filename === 'Generic') {
continue;
}
// Valid coding standard dirs include a standard class.
$csFile = $file->getPathname().'/ruleset.xml';
if (is_file($csFile) === true) {
// We found a coding standard directory.
$installedStandards[] = $filename;
}
}
}
return $installedStandards;
}//end getInstalledStandards()
/**
* Determine if a standard is installed.
*
* Coding standards are directories located in the
* CodeSniffer/Standards directory. Valid coding standards
* include a Sniffs subdirectory.
*
* @param string $standard The name of the coding standard.
*
* @return boolean
* @see getInstalledStandards()
*/
public static function isInstalledStandard($standard)
{
$path = self::getInstalledStandardPath($standard);
if ($path !== null) {
return true;
} else {
// This could be a custom standard, installed outside our
// standards directory.
$ruleset = rtrim($standard, ' /\\').DIRECTORY_SEPARATOR.'ruleset.xml';
if (is_file($ruleset) === true) {
return true;
}
// Might also be an actual ruleset file itself.
// If it has an XML extension, let's at least try it.
if (is_file($standard) === true
&& substr(strtolower($standard), -4) === '.xml'
) {
return true;
}
}
return false;
}//end isInstalledStandard()
/**
* Return the path of an installed coding standard.
*
* Coding standards are directories located in the
* CodeSniffer/Standards directory. Valid coding standards
* include a Sniffs subdirectory.
*
* @param string $standard The name of the coding standard.
*
* @return string|null
*/
public static function getInstalledStandardPath($standard)
{
$path = realpath(dirname(__FILE__).'/CodeSniffer/Standards/'.$standard.'/ruleset.xml');
if (is_file($path) === true) {
return $path;
}
return null;
}//end getInstalledStandardPath()
/**
* Get a single config value.
*
* Config data is stored in the data dir, in a file called
* CodeSniffer.conf. It is a simple PHP array.
*
* @param string $key The name of the config value.
*
* @return string
* @see setConfigData()
* @see getAllConfigData()
*/
public static function getConfigData($key)
{
$phpCodeSnifferConfig = self::getAllConfigData();
if ($phpCodeSnifferConfig === null) {
return null;
}
if (isset($phpCodeSnifferConfig[$key]) === false) {
return null;
}
return $phpCodeSnifferConfig[$key];
}//end getConfigData()
/**
* Set a single config value.
*
* Config data is stored in the data dir, in a file called
* CodeSniffer.conf. It is a simple PHP array.
*
* @param string $key The name of the config value.
* @param string|null $value The value to set. If null, the config
* entry is deleted, reverting it to the
* default value.
* @param boolean $temp Set this config data temporarily for this
* script run. This will not write the config
* data to the config file.
*
* @return boolean
* @see getConfigData()
* @throws PHP_CodeSniffer_Exception If the config file can not be written.
*/
public static function setConfigData($key, $value, $temp=false)
{
if ($temp === false) {
$configFile = '/etc/php-codesniffer/CodeSniffer.conf';
if (is_file($configFile) === false
&& strpos('/usr/share/php/data', '@data_dir') === false
) {
// If data_dir was replaced, this is a PEAR install and we can
// use the PEAR data dir to store the conf file.
$configFile = '/usr/share/php/data/PHP_CodeSniffer/CodeSniffer.conf';
}
if (is_file($configFile) === true
&& is_writable($configFile) === false
) {
$error = "Config file $configFile is not writable";
throw new PHP_CodeSniffer_Exception($error);
}
}
$phpCodeSnifferConfig = self::getAllConfigData();
if ($value === null) {
if (isset($phpCodeSnifferConfig[$key]) === true) {
unset($phpCodeSnifferConfig[$key]);
}
} else {
$phpCodeSnifferConfig[$key] = $value;
}
if ($temp === false) {
$output = '<'.'?php'."\n".' $phpCodeSnifferConfig = ';
$output .= var_export($phpCodeSnifferConfig, true);
$output .= "\n?".'>';
if (file_put_contents($configFile, $output) === false) {
return false;
}
}
$GLOBALS['PHP_CODESNIFFER_CONFIG_DATA'] = $phpCodeSnifferConfig;
return true;
}//end setConfigData()
/**
* Get all config data in an array.
*
* @return string
* @see getConfigData()
*/
public static function getAllConfigData()
{
if (isset($GLOBALS['PHP_CODESNIFFER_CONFIG_DATA']) === true) {
return $GLOBALS['PHP_CODESNIFFER_CONFIG_DATA'];
}
$configFile = '/etc/php-codesniffer/CodeSniffer.conf';
if (is_file($configFile) === false) {
$configFile = '/usr/share/php/data/PHP_CodeSniffer/CodeSniffer.conf';
}
if (is_file($configFile) === false) {
return null;
}
include $configFile;
$GLOBALS['PHP_CODESNIFFER_CONFIG_DATA'] = $phpCodeSnifferConfig;
return $GLOBALS['PHP_CODESNIFFER_CONFIG_DATA'];
}//end getAllConfigData()
}//end class
?>
|