public function __construct($dir, $full = false, $rec = false, $dirs = true)
{
// Check to see if the directory exists.
if (!file_exists(dirname($dir))) {
throw new Exception('Error: The directory does not exist.');
}
$this->tree[realpath($dir)] = $this->buildTree(new \DirectoryIterator($dir));
$this->full = $full;
$this->rec = $rec;
$this->dirs = $dirs;
// Set the directory path.
if (strpos($dir, '/') !== false && DIRECTORY_SEPARATOR != '/') {
$this->path = str_replace('/', "\\", $dir);
} else {
if (strpos($dir, "\\") !== false && DIRECTORY_SEPARATOR != "\\") {
$this->path = str_replace("\\", '/', $dir);
} else {
$this->path = $dir;
}
}
// Trim the trailing slash.
if (strrpos($this->path, DIRECTORY_SEPARATOR) == strlen($this->path) - 1) {
$this->path = substr($this->path, 0, -1);
}
// If the recursive flag is passed, traverse recursively.
if ($this->rec) {
$objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->path), \RecursiveIteratorIterator::SELF_FIRST);
foreach ($objects as $fileInfo) {
if ($fileInfo->getFilename() != '.' && $fileInfo->getFilename() != '..') {
// If full path flag was passed, store the full path.
if ($this->full) {
$f = null;
if ($this->dirs) {
$f = $fileInfo->isDir() ? realpath($fileInfo->getPathname()) : realpath($fileInfo->getPathname());
} else {
if (!$fileInfo->isDir()) {
$f = realpath($fileInfo->getPathname());
}
}
if (null !== $f) {
$this->files[] = $f;
$this->objects[] = $f;
}
// Else, store only the directory or file name.
} else {
if ($this->dirs) {
$this->files[] = $fileInfo->isDir() ? $fileInfo->getFilename() : $fileInfo->getFilename();
$this->objects[] = $fileInfo->isDir() ? realpath($fileInfo->getPathname()) : realpath($fileInfo->getPathname());
} else {
if (!$fileInfo->isDir()) {
$this->files[] = $fileInfo->getFilename();
$this->objects[] = realpath($fileInfo->getPathname());
}
}
}
}
}
// Else, only traverse the single directory that was passed.
} else {
foreach (new \DirectoryIterator($this->path) as $fileInfo) {
if (!$fileInfo->isDot()) {
// If full path flag was passed, store the full path.
if ($this->full) {
if ($this->dirs) {
$f = $fileInfo->isDir() ? $this->path . DIRECTORY_SEPARATOR . $fileInfo->getFilename() . DIRECTORY_SEPARATOR : $this->path . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
} else {
if (!$fileInfo->isDir()) {
$f = $this->path . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
}
}
$this->files[] = $f;
$this->objects[] = $f;
// Else, store only the directory or file name.
} else {
if ($this->dirs) {
$this->files[] = $fileInfo->isDir() ? $fileInfo->getFilename() : $fileInfo->getFilename();
$this->objects[] = $fileInfo->isDir() ? $this->path . DIRECTORY_SEPARATOR . $fileInfo->getFilename() . DIRECTORY_SEPARATOR : $this->path . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
} else {
if (!$fileInfo->isDir()) {
$this->files[] = $fileInfo->getFilename();
$this->objects[] = $this->path . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
}
}
}
}
}
}
}