Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
function processDirectory($start = './', $format = 'array') {
if (!empty($start)) {
$start = rtrim($start, '/') . '/';
}
if (!empty($start) && !is_dir($start)) {
return 'json' === $format ? 'false' : false;
}
$result = [];
$flags = FilesystemIterator::KEY_AS_PATHNAME
| FilesystemIterator::CURRENT_AS_FILEINFO
| FilesystemIterator::SKIP_DOTS;
$directory = new DirectoryIterator($start);
foreach ($directory as $dir) {
if ($dir->isDir() && !$dir->isDot()) {
$files = $duplicates = $size = 0;
$md5 = [];
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir->getPathname(), $flags));
foreach ($iterator as $file) {
$files++;
$size += $file->getSize();
$hash = md5_file($file->getPathname());
if (empty($md5[$hash])) {
$md5[$hash] = 1;
} else {
$duplicates++;
}
}
$result[$dir->getFilename()] = [
'total_size' => $size,
'files' => $files,
'duplicates' => $duplicates,
];
}
}
if (!empty($result)) {
uasort($result, function ($a, $b) {
if ($a['total_size'] > $b['total_size']) {
return 1;
}
if ($a['total_size'] < $b['total_size']) {
return -1;
}
return 0;
});
}
return 'json' === $format ? json_encode($result) : $result;
}
if (!empty($argv[1])) {
var_export(processDirectory($argv[1], !empty($argv[2]) ? $argv[2] : 'array'));
} else {
var_export(processDirectory());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.