1
0
Fork 0

add public method Filesystem#size

pull/1422/head
Galymzhan 2012-12-17 01:04:39 +06:00
parent 51eca2cdfc
commit 69f2230a4c
2 changed files with 52 additions and 0 deletions

View File

@ -269,6 +269,38 @@ class Filesystem
return substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':';
}
/**
* Returns size of a file or directory specified by path. If a directory is
* given, it's size will be computed recursively.
*
* @param string $path Path to the file or directory
* @return int
*/
public function size($path)
{
if (!file_exists($path)) {
throw new \RuntimeException("$path does not exist.");
}
if (is_dir($path)) {
return $this->directorySize($path);
}
return filesize($path);
}
protected function directorySize($directory)
{
$it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
$size = 0;
foreach ($ri as $file) {
if ($file->isFile()) {
$size += $file->getSize();
}
}
return $size;
}
protected function getProcess()
{
return new ProcessExecutor;

View File

@ -107,5 +107,25 @@ class FilesystemTest extends TestCase
$this->assertTrue($fs->removeDirectoryPhp($tmp . "/composer_testdir"));
$this->assertFalse(file_exists($tmp . "/composer_testdir/level1/level2/hello.txt"));
}
public function testFileSize()
{
$tmp = sys_get_temp_dir();
file_put_contents("$tmp/composer_test_file", 'Hello');
$fs = new Filesystem;
$this->assertGreaterThanOrEqual(5, $fs->size("$tmp/composer_test_file"));
}
public function testDirectorySize()
{
$tmp = sys_get_temp_dir();
@mkdir("$tmp/composer_testdir", 0777, true);
file_put_contents("$tmp/composer_testdir/file1.txt", 'Hello');
file_put_contents("$tmp/composer_testdir/file2.txt", 'World');
$fs = new Filesystem;
$this->assertGreaterThanOrEqual(10, $fs->size("$tmp/composer_testdir"));
}
}