Created
October 25, 2016 08:00
-
-
Save spirit-q2/d8d9c9471a26c92e4411508afbe82c5f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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