add public method Filesystem#size
parent
51eca2cdfc
commit
69f2230a4c
|
@ -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;
|
||||
|
|
|
@ -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"));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue