Skip to content

Instantly share code, notes, and snippets.

@culttm
Created December 21, 2016 13:58
Show Gist options
  • Select an option

  • Save culttm/813331523cc2b9151f0f3626d2a296af to your computer and use it in GitHub Desktop.

Select an option

Save culttm/813331523cc2b9151f0f3626d2a296af to your computer and use it in GitHub Desktop.
function file_scan_directory($dir, $mask, $options = array(), $depth = 0) {
// Merge in defaults.
$options += array(
'nomask' => '/(\.\.?|CVS|node_modules|bower_components)$/',
'callback' => 0,
'recurse' => TRUE,
'key' => 'uri',
'min_depth' => 0,
);
$options['key'] = in_array($options['key'], array('uri', 'filename', 'name')) ? $options['key'] : 'uri';
$files = array();
if (is_dir($dir) && $handle = opendir($dir)) {
while (FALSE !== ($filename = readdir($handle))) {
if (!preg_match($options['nomask'], $filename) && $filename[0] != '.') {
$uri = "$dir/$filename";
$uri = file_stream_wrapper_uri_normalize($uri);
if (is_dir($uri) && $options['recurse']) {
if (FALSE !== strpos($uri, 'node_modules')) {
die($uri);
}
// Give priority to files in this folder by merging them in after any subdirectory files.
$files = array_merge(file_scan_directory($uri, $mask, $options, $depth + 1), $files);
}
elseif ($depth >= $options['min_depth'] && preg_match($mask, $filename)) {
// Always use this match over anything already set in $files with the
// same $$options['key'].
$file = new stdClass();
$file->uri = $uri;
$file->filename = $filename;
$file->name = pathinfo($filename, PATHINFO_FILENAME);
$key = $options['key'];
$files[$file->$key] = $file;
if ($options['callback']) {
$options['callback']($uri);
}
}
}
}
closedir($handle);
}
return $files;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment