View source
<?php
namespace Drupal\gutenberg;
class ScanDir {
private static $directories;
private static $files;
private static $extFilter;
private static $recursive;
public static function scan($root_dirs, $extension_filters = NULL, $recursive = FALSE) {
self::$recursive = FALSE;
self::$directories = [];
self::$files = [];
self::$extFilter = FALSE;
if (!is_string($root_dirs) && !is_array($root_dirs)) {
throw new \LogicException('Must provide a path string or array of path strings');
}
self::$recursive = $recursive;
if (isset($extension_filters)) {
if (is_array($extension_filters)) {
self::$extFilter = array_map('strtolower', $extension_filters);
}
elseif (is_string($extension_filters)) {
self::$extFilter[] = strtolower($extension_filters);
}
}
if (is_string($root_dirs)) {
$root_dirs = [
$root_dirs,
];
}
self::verifyPaths($root_dirs);
return array_map(function ($entry) use ($root_dirs) {
$asset = $entry;
foreach ($root_dirs as $root_dir) {
$root_dir .= DIRECTORY_SEPARATOR;
$root_dir_length = strlen($root_dir);
if (substr($entry, 0, $root_dir_length) === $root_dir) {
$asset = substr($entry, $root_dir_length);
break;
}
}
if ('\\' === \DIRECTORY_SEPARATOR) {
$asset = str_replace(DIRECTORY_SEPARATOR, '/', $asset);
}
return $asset;
}, self::$files);
}
private static function verifyPaths(array $paths) {
$path_errors = [];
foreach ($paths as $path) {
if (is_dir($path)) {
self::$directories[] = $path;
self::findContents($path);
}
else {
$path_errors[] = $path;
}
}
if ($path_errors) {
throw new \RuntimeException("The following directories do not exists\n" . var_export($path_errors, TRUE));
}
}
private static function findContents($dir) {
$result = [];
$root = scandir($dir);
foreach ($root as $value) {
if ($value === '.' || $value === '..') {
continue;
}
if (is_file($dir . DIRECTORY_SEPARATOR . $value)) {
if (!self::$extFilter || in_array(strtolower(pathinfo($dir . DIRECTORY_SEPARATOR . $value, PATHINFO_EXTENSION)), self::$extFilter)) {
self::$files[] = $result[] = $dir . DIRECTORY_SEPARATOR . $value;
}
continue;
}
if (self::$recursive) {
foreach (self::findContents($dir . DIRECTORY_SEPARATOR . $value) as $entry) {
self::$files[] = $result[] = $entry;
}
}
}
return $result;
}
}