| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Recurses each directory and runs PHP's lint function against each file to test for parse errors. |
| 5 | * |
| 6 | * @since 4.0.0 |
| 7 | * |
| 8 | * @param string $dir The directory you would like to start from. |
| 9 | * @return array The files that did not pass the test. |
| 10 | */ |
| 11 | function bp_lint( $dir ) { |
| 12 | static $failed = array(); |
| 13 | |
| 14 | $excluded_dirs = array(); |
| 15 | $excluded_files = array(); |
| 16 | |
| 17 | foreach ( new RecursiveDirectoryIterator( $dir ) as $path => $objSplFileInfo ) { |
| 18 | // Recurse if directory. |
| 19 | if ( $objSplFileInfo->isDir() ) { |
| 20 | if ( stristr( $objSplFileInfo->getFileName(), '.svn' ) !== false ) { |
| 21 | continue; |
| 22 | } |
| 23 | |
| 24 | if ( '.' === $objSplFileInfo->getFileName() || '..' === $objSplFileInfo->getFileName() ) { |
| 25 | continue; |
| 26 | } |
| 27 | |
| 28 | $relativePath = bp_lint_get_relative_path( $objSplFileInfo->getRealPath() ); |
| 29 | |
| 30 | if ( in_array( $relativePath, $excluded_dirs, true ) ) { |
| 31 | continue; |
| 32 | } |
| 33 | |
| 34 | bp_lint( $objSplFileInfo->getPathName() ); |
| 35 | |
| 36 | continue; |
| 37 | } |
| 38 | |
| 39 | // are there any non-dirs that aren't files? |
| 40 | if ( ! $objSplFileInfo->isFile() ) { |
| 41 | throw new UnexpectedValueException( 'Not a dir and not a file?' ); |
| 42 | } |
| 43 | |
| 44 | // skip non-php files |
| 45 | if ( preg_match( '#\.php$#', $objSplFileInfo->getFileName() ) !== 1 ) { |
| 46 | continue; |
| 47 | } |
| 48 | |
| 49 | // Blacklist. |
| 50 | $relativePath = bp_lint_get_relative_path( $objSplFileInfo ); |
| 51 | if ( in_array( $relativePath, $excluded_files, true ) ) { |
| 52 | continue; |
| 53 | } |
| 54 | |
| 55 | // Perform the lint check. |
| 56 | $result = exec( 'php -l ' . escapeshellarg( $objSplFileInfo ) ); |
| 57 | if ( preg_match( '#^No syntax errors detected in#', $result ) !== 1 ) { |
| 58 | $failed[ $objSplFileInfo->getPathName() ] = $result; |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | echo '.'; |
| 63 | return $failed; |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Gets a relative path. |
| 68 | * |
| 69 | * @since 4.0.0 |
| 70 | * |
| 71 | * @param string $path Full path. |
| 72 | * @return string |
| 73 | */ |
| 74 | function bp_lint_get_relative_path( $path ) { |
| 75 | return str_replace( realpath( __DIR__ . '/../' ), '', $path ); |
| 76 | } |
| 77 | |
| 78 | echo 'Linting...'; |
| 79 | $failed = bp_lint( realpath( $argv[1] ) ); |
| 80 | echo "\n"; |
| 81 | if ( empty( $failed ) ) { |
| 82 | echo 'All checks passed.' . "\n"; |
| 83 | exit( 0 ); |
| 84 | } else { |
| 85 | echo 'Errors found in the following files:' . "\n"; |
| 86 | print_r( $failed ); |
| 87 | echo "\n"; |
| 88 | exit( 1 ); |
| 89 | } |