Skip to content

Commit b37e89c

Browse files
committed
Add ability to add/subtract arrays
1 parent c19f597 commit b37e89c

File tree

3 files changed

+49
-2
lines changed

3 files changed

+49
-2
lines changed

README.md

+6
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,12 @@ $size->add('2G')
6060
echo $size->asAuto(); // '10.00 GB'
6161
```
6262

63+
You may also use `add()` and `subtract()` with an array of values:
64+
65+
```
66+
$size->add(['50mb', '140mb', '1.2mb']);
67+
```
68+
6369
### Number base
6470

6571
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:

src/FileSize.php

+32-2
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,43 @@ private function sizeToBytes($size)
6363
return $this->convert($value, $unit, UnitMap::BYTE);
6464
}
6565

66+
/**
67+
* Add one or many filesizes.
68+
*
69+
* @param array|string|int $sizes
70+
* @return self
71+
*/
72+
public function add($sizes)
73+
{
74+
foreach ((array) $sizes as $size) {
75+
$this->addSize($size);
76+
}
77+
78+
return $this;
79+
}
80+
81+
/**
82+
* Subtract one or many filesizes.
83+
*
84+
* @param array|string|int $sizes
85+
* @return self
86+
*/
87+
public function subtract($sizes)
88+
{
89+
foreach ((array) $sizes as $size) {
90+
$this->subtractSize($size);
91+
}
92+
93+
return $this;
94+
}
95+
6696
/**
6797
* Add to this filesize.
6898
*
6999
* @param string|int $size Such as '100 MB'
70100
* @return self
71101
*/
72-
public function add($size)
102+
private function addSize($size)
73103
{
74104
$this->bytes += $this->sizeToBytes($size);
75105

@@ -82,7 +112,7 @@ public function add($size)
82112
* @param string|int $size Such as '100 MB'
83113
* @return self
84114
*/
85-
public function subtract($size)
115+
private function subtractSize($size)
86116
{
87117
$bytesToSubtract = $this->sizeToBytes($size);
88118

tests/FileSizeTest.php

+11
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,17 @@ public function testSubtract()
5252
$this->assertSame($size->as('B'), 128821248);
5353
}
5454

55+
/**
56+
* Test adding an array of items.
57+
*/
58+
public function testAddMany()
59+
{
60+
$size = new FileSize();
61+
$size->add(['50mb', '140mb', '1.2mb']);
62+
63+
$this->assertSame($size->as('MB'), 191.2);
64+
}
65+
5566
/**
5667
* Test #multiplyBy.
5768
*/

0 commit comments

Comments
 (0)