View source
<?php
namespace Drupal\gutenberg;
class ScanDir {
private static $directories;
private static $files;
private static $extFilter;
private static $recursive;
public static function scan() {
self::$recursive = FALSE;
self::$directories = [];
self::$files = [];
self::$extFilter = FALSE;
if (!($args = func_get_args())) {
die("Must provide a path string or array of path strings");
}
if (gettype($args[0]) != "string" && gettype($args[0]) != "array") {
die("Must provide a path string or array of path strings");
}
if (isset($args[2]) && $args[2] == TRUE) {
self::$recursive = TRUE;
}
if (isset($args[1])) {
if (gettype($args[1]) == "array") {
self::$extFilter = array_map('strtolower', $args[1]);
}
elseif (gettype($args[1]) == "string") {
self::$extFilter[] = strtolower($args[1]);
}
}
self::verifyPaths($args[0]);
return array_map(function ($entry) {
return substr($entry, 3, strlen($entry) - 1);
}, self::$files);
}
private static function verifyPaths($paths) {
$path_errors = [];
if (gettype($paths) == "string") {
$paths = [
$paths,
];
}
foreach ($paths as $path) {
if (is_dir($path)) {
self::$directories[] = $path;
$dirContents = self::findContents($path);
}
else {
$path_errors[] = $path;
}
}
if ($path_errors) {
echo "The following directories do not exists<br />";
die(var_dump($path_errors));
}
}
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 $value) {
self::$files[] = $result[] = $value;
}
}
}
return $result;
}
}