Browse Source

add public method Filesystem#size

Galymzhan 12 years ago
parent
commit
69f2230a4c
2 changed files with 52 additions and 0 deletions
  1. 32 0
      src/Composer/Util/Filesystem.php
  2. 20 0
      tests/Composer/Test/Util/FilesystemTest.php

+ 32 - 0
src/Composer/Util/Filesystem.php

@@ -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;

+ 20 - 0
tests/Composer/Test/Util/FilesystemTest.php

@@ -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"));
+    }
 }