Skip to content

Commit

Permalink
Add ability to add/subtract arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisullyott committed Aug 28, 2019
1 parent c19f597 commit b37e89c
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
34 changes: 32 additions & 2 deletions src/FileSize.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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);

Expand Down
11 changes: 11 additions & 0 deletions tests/FileSizeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down

0 comments on commit b37e89c

Please sign in to comment.