效果图:
try
{
$directories = new FileSystem('C:\Program Files (x86)\Windows NT');
$files = $directories->getFiles();
var_dump($files);
} catch (Exception $e) {
}
class FileSystem
{
/**
* 文件名称升序
* @var int
*/
public const SORT_ASC = 1;
/**
* 文件名称降序
* @var int
*/
public const SORT_DESC = 0;
/**
* @var string $dir
*/
private $directory;
/**
* FileSystem constructor.
* @param string $directory
*/
public function __construct(string $directory)
{
$this->directory = $directory;
}
/**
* @return array
* @throws Exception
*/
public function getFiles() : array
{
$files = [];
$directory = $this->directory;
foreach ( $directories = self::getDirectories($directory, self::SORT_ASC) as $directory)
{
$fileSystemIterator = new \FilesystemIterator($directory);
/**
* @var $fileInfo SplFileInfo
*/
foreach ($fileSystemIterator as $fileInfo)
{
// 文件内容是否为空
if ($fileInfo->getSize() > 0 && $fileInfo->isFile()) {
$files[] = sprintf("%s%s%s", $directory, self::separator() , $fileInfo->getFilename());
}
}
}
return $files;
}
public static function separator()
{
return PHP_OS === 'WINNT'? '\\':DIRECTORY_SEPARATOR;
}
/**
* @param string $dir
* @param int $sort
* @return array
* @throws Exception
*/
public static function getDirectories(string $dir, $sort = self::SORT_DESC) : array
{
$dirs = [];
$directories = scandir($dir,$sort);
if ($directories === false) {
throw new Exception('open dir fail.');
}
foreach ($directories as $dirname) {
if ($dirname === '.' || $dirname === '..') {
continue;
}
$directory = "{$dir}".self::separator()."{$dirname}";
if (is_dir($directory))
{
$dirs[] = $directory;
$dirs = array_merge($dirs, self::getDirectories($directory));
}
}
return $dirs;
}
}
|