<?php
/**
* Class for getting content of some directory.
*
* This class can also retrieve content of all subdirectories
* in some folder.
*
* @author Nikola Posa <hide@address.com>
* @license GNU General Public License
*/
class DirContent
{
/**
* Directory path.
*
* @var string
*/
protected $path;
/**
* Constructor.
*
* @param string Path to directory.
* @return void
*/
public function __construct($path = null)
{
if ($path != null) {
$this->setPath($path);
}
$this->setupPath();
}
/**
* Sets path to directory.
*
* @param string Path to directory.
* @return void
*/
public function setPath($path)
{
$this->path = (string) $path;
}
/**
* Checking path, and setting it up, without trailing slash.
*
* @return void
*/
protected function setupPath()
{
if (($length = strlen($this->path)) == 0 || !is_dir($this->path)) {
throw new Exception('Please supply valid directory path.');
}
elseif ($this->path{$length - 1} == '/') {
$this->setPath(substr($this->path, -1));
}
}
/**
* Gets content of a directory.
*
* @param mixed How to sort dir/file names. (optional)
* @param bool Whether to recursively retrieve contents of subdirs, too.
* @param array What dirs to omit (used only if subDirs param is set to true).
* @param string Path of the directory that is currently being processed. Used in recursive calls.
* @return void
*/
public function getContent($sortBy = null, $subDirs = true, $omit = array(), $path = '')
{
//No path supplied, or calling this function for the first time.
if (strlen($path) == 0) {
$path = $this->path;
}
$content = array();
@ $files = scandir($path);
//Has some files?
if ($files != false) {
if ($sortBy != null) { //Sorting type passed? Do the sorting.
$files = DirContent_Sort::sort($path, $files, $sortBy);
}
foreach ($files as $file) {
if ($file == '.' || $file == '..') { //We don't need those characters.
continue;
}
$filePath = $path . '/' . $file;
if (is_dir($filePath)) { //Folder?
//If subDirs flag is set to true and dir isn't in list of dirs to be ommited, we should retrieve content of that dir, too.
if ($subDirs == true && !in_array($file, $omit)) {
$content[$file] = $this->getContent($sortBy, $subDirs, $omit, $filePath); //Recursive function call.
}
else {
$content[] = $file;
}
}
elseif (is_file($filePath)) { //File? Simply store its name into returning array.
$content[] = $file;
}
}
}
return $content;
}
}
?>