diff --git a/src/IterableCodeExtractor.php b/src/IterableCodeExtractor.php index 11af44ec..f0206ebe 100644 --- a/src/IterableCodeExtractor.php +++ b/src/IterableCodeExtractor.php @@ -161,8 +161,6 @@ protected static function containsMatchingChildren( SplFileInfo $dir, array $mat $root_relative_path = str_replace( static::$dir, '', $dir->getPathname() ); foreach ( $matchers as $path_or_file ) { - $path_or_file = ltrim( $path_or_file, '/' ); - // If the matcher contains no wildcards and the path matches the start of the matcher. if ( '' !== $root_relative_path && @@ -206,21 +204,26 @@ public static function getFilesFromDirectory( $dir, array $include = [], array $ function ( $file, $key, $iterator ) use ( $include, $exclude, $extensions ) { /** @var RecursiveCallbackFilterIterator $iterator */ /** @var SplFileInfo $file */ + + // Normalize include and exclude paths. + $include = array_map( 'static::trim_leading_slash', $include ); + $exclude = array_map( 'static::trim_leading_slash', $exclude ); + // If no $include is passed everything gets the weakest possible matching score. $inclusion_score = empty( $include ) ? 0.1 : static::calculateMatchScore( $file, $include ); $exclusion_score = static::calculateMatchScore( $file, $exclude ); // Always include directories that aren't excluded. - if ( $file->isDir() && 0 === $exclusion_score ) { + if ( 0 === $exclusion_score && $iterator->hasChildren() ) { return true; } - if ( $file->isDir() && ( 0 === $inclusion_score || $exclusion_score > $inclusion_score ) ) { + if ( ( 0 === $inclusion_score || $exclusion_score > $inclusion_score ) && $iterator->hasChildren() ) { // Always include directories that may have matching children even if they are excluded. return static::containsMatchingChildren( $file, $include ); } - return ( $file->isFile() && in_array( $file->getExtension(), $extensions, true ) ); + return ( ( $inclusion_score >= $exclusion_score ) && $file->isFile() && in_array( $file->getExtension(), $extensions, true ) ); } ), RecursiveIteratorIterator::CHILD_FIRST @@ -239,4 +242,14 @@ function ( $file, $key, $iterator ) use ( $include, $exclude, $extensions ) { return $filtered_files; } + + /** + * Trim leading slash from a path. + * + * @param string $path Path to trim. + * @return string Trimmed path. + */ + private static function trim_leading_slash( $path ) { + return ltrim( $path, '/' ); + } }