diff --git a/README.md b/README.md index 2ca816f..24d0402 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,12 @@ $size->add('2G') echo $size->asAuto(); // '10.00 GB' ``` +You may also use `add()` and `subtract()` with an array of values: + +``` +$size->add(['50mb', '140mb', '1.2mb']); +``` + ### Number base The second argument of the constructor is the number base, which accepts either `2` (binary) or `10` (decimal). We use binary by default. To handle sizes in decimal: diff --git a/src/FileSize.php b/src/FileSize.php index 844b6bc..b1b7580 100644 --- a/src/FileSize.php +++ b/src/FileSize.php @@ -63,13 +63,43 @@ private function sizeToBytes($size) return $this->convert($value, $unit, UnitMap::BYTE); } + /** + * Add one or many filesizes. + * + * @param array|string|int $sizes + * @return self + */ + public function add($sizes) + { + foreach ((array) $sizes as $size) { + $this->addSize($size); + } + + return $this; + } + + /** + * Subtract one or many filesizes. + * + * @param array|string|int $sizes + * @return self + */ + public function subtract($sizes) + { + foreach ((array) $sizes as $size) { + $this->subtractSize($size); + } + + return $this; + } + /** * Add to this filesize. * * @param string|int $size Such as '100 MB' * @return self */ - public function add($size) + private function addSize($size) { $this->bytes += $this->sizeToBytes($size); @@ -82,7 +112,7 @@ public function add($size) * @param string|int $size Such as '100 MB' * @return self */ - public function subtract($size) + private function subtractSize($size) { $bytesToSubtract = $this->sizeToBytes($size); diff --git a/tests/FileSizeTest.php b/tests/FileSizeTest.php index 9840c7f..8608ef7 100644 --- a/tests/FileSizeTest.php +++ b/tests/FileSizeTest.php @@ -52,6 +52,17 @@ public function testSubtract() $this->assertSame($size->as('B'), 128821248); } + /** + * Test adding an array of items. + */ + public function testAddMany() + { + $size = new FileSize(); + $size->add(['50mb', '140mb', '1.2mb']); + + $this->assertSame($size->as('MB'), 191.2); + } + /** * Test #multiplyBy. */