DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Love has posted 1 posts at DZone. View Full User Profile

parse glob style path string

12.29.2013
| 2056 views |
  • submit to reddit
/**
*
* @param mixed VARGS: any number of strings or arrays, each being a file path or a glob to watch.
* @return array The set of files matches the passed globs.
*/
function recursive_glob($requestedGlobs)
{
    // expoode vargs
    $requestedGlobs = array();
    foreach (func_get_args() as $arg) {
        if (!is_array($arg))
        {
            $arg = array($arg);
        }
        $requestedGlobs = array_merge($requestedGlobs, $arg);
    }
    $requestedGlobs = array_unique($requestedGlobs);

    // expand all a/b/**/c/*.foo into globs
    $globsToProcess = array();
    foreach ($requestedGlobs as $glob) {
        $hasRecursiveDirGlob = (strpos($glob, '**') !== false);
        if ($hasRecursiveDirGlob)
        {
            list($baseDir, $subGlob) = explode('**', $glob, 2);
            $baseDir = rtrim($baseDir, '/');
            $subGlob = ltrim($subGlob, '/');

            // root glob
            $globsToProcess[] = "{$baseDir}/{$subGlob}";

            $rDirIterator = new RecursiveDirectoryIterator($baseDir);
            $itIterator = new RecursiveIteratorIterator($rDirIterator, RecursiveIteratorIterator::CHILD_FIRST);
            foreach ($itIterator as $path => $fileInfo) {
                if ($itIterator->getInnerIterator()->isDot()) continue;
                if ($itIterator->getInnerIterator()->isFile()) continue;

                $globsToProcess[] = "{$path}/{$subGlob}";
            }
        }
        else
        {
            $globsToProcess[] = $glob;
        }
    }

    $matches = array();
    $globsToProcess = array_unique($globsToProcess);
    foreach ($globsToProcess as $glob) {
        $matches = array_merge($matches, glob($glob));
    }

    $matches = array_unique($matches);
    return $matches;
}